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: add executive-control POST drills (#4445)
[._.]/ Adam Eivy1d5ad638521d
diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsxindex a11ddb1134..8ddcfdb069 100644--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx@@ -59,6 +59,12 @@ function renderCognitiveDrill(shared) {return <MentalRotationRunner {...shared} />;case 'reaction-time':return <ReactionTimeRunner {...shared} />;+ case 'task-switching':+ return <TaskSwitchingRunner {...shared} />;+ case 'go-no-go':+ return <GoNoGoRunner {...shared} />;+ case 'flanker':+ return <FlankerRunner {...shared} />;default:return <div className="text-port-error text-center py-8">Unsupported cognitive drill: {shared.drill.type}</div>;}@@ -170,6 +176,36 @@ export function getDrillTutorial(drill) {controls: choice ? 'Number keys, or tap the lit box.' : 'Space / Enter, or tap.',};}+ case 'task-switching':+ return {+ goal: 'Use the rule cue to classify each stimulus, switching rules when the cue changes.',+ steps: [+ 'Read the rule cue first: color, shape, or fill.',+ 'When the stimulus appears, answer using only that rule and ignore its other attributes.',+ 'Rule changes and conflicting attributes are deliberate — accuracy comes before speed.',+ ],+ controls: 'Tap Left / Right, or press the Left / Right arrow key.',+ };+ case 'go-no-go':+ return {+ goal: 'Respond to go signals and withhold your response to no-go lures.',+ steps: [+ 'A symbol appears briefly on every trial.',+ 'Tap or press Space for a green go signal.',+ 'Do nothing for a no-go lure; the next trial advances at the deadline.',+ ],+ controls: 'Tap the signal, or press Space / Enter. Withhold on no-go.',+ };+ case 'flanker':+ return {+ goal: 'Report the center arrow while ignoring the surrounding arrows.',+ steps: [+ 'A row of arrows appears.',+ 'Answer the direction of the center arrow only.',+ 'The outer arrows may agree or conflict; keep attention on the center.',+ ],+ controls: 'Tap Left / Right, or press the Left / Right arrow key.',+ };default:return null;}@@ -305,6 +341,93 @@ export function localSchulteMetrics(drill, questions) {return { score, accuracy, completion, avgResponseMs, answeredCount, totalCount, attemptCount, errorCount };}+function localAverageLatency(questions) {+ const timed = questions.filter(question => question.correct && question.responseMs > 0);+ return timed.length ? Math.round(timed.reduce((sum, question) => sum + question.responseMs, 0) / timed.length) : null;+}++function localGroupAccuracy(questions, predicate) {+ const group = questions.filter(predicate);+ return group.length ? group.filter(question => question.correct).length / group.length : null;+}++function localCost(questions, costlyPredicate, baselinePredicate) {+ const costly = localAverageLatency(questions.filter(costlyPredicate));+ const baseline = localAverageLatency(questions.filter(baselinePredicate));+ return costly == null || baseline == null ? null : costly - baseline;+}++function localExecutiveMetrics(questions, totalCount = questions.length, refMs = 1800) {+ const answered = questions.filter(question => question.answered != null);+ const accuracy = questions.length ? questions.filter(question => question.correct).length / questions.length : null;+ const completion = totalCount ? questions.length / totalCount : null;+ const avgResponseMs = localAverageLatency(questions);+ const speedBonus = avgResponseMs == null ? 0 : Math.max(0, 1 - avgResponseMs / refMs);+ return {+ score: Math.round(((accuracy || 0) * 0.8 + speedBonus * 0.2) * (completion || 0) * 100),+ accuracy,+ completion,+ avgResponseMs,+ answeredCount: answered.length,+ totalCount,+ commissionErrors: answered.filter(question => !question.correct).length,+ omissions: questions.filter(question => question.answered == null && !question.correct).length,+ latencyDistributionMs: answered.map(question => question.responseMs).filter(ms => ms > 0),+ };+}++export function localTaskSwitchMetrics(questions, totalCount, refMs) {+ return {+ ...localExecutiveMetrics(questions, totalCount, refMs),+ switchCostMs: localCost(questions, question => question.switched, question => !question.switched),+ switchAccuracy: localGroupAccuracy(questions, question => question.switched),+ repeatAccuracy: localGroupAccuracy(questions, question => !question.switched),+ };+}++export function localGoNoGoMetrics(questions, totalCount = questions.length) {+ const hits = questions.filter(question => !question.noGo && question.answered === 'go').length;+ const omissions = questions.filter(question => !question.noGo && question.answered == null).length;+ const falseAlarms = questions.filter(question => question.noGo && question.answered === 'go').length;+ const correctRejections = questions.filter(question => question.noGo && question.answered == null).length;+ const goCount = hits + omissions;+ const noGoCount = falseAlarms + correctRejections;+ const accuracy = goCount || noGoCount+ ? ((goCount ? hits / goCount : 0.5) + (noGoCount ? correctRejections / noGoCount : 0.5)) / 2+ : null;+ const latencies = questions.filter(question => question.answered === 'go' && question.responseMs > 0).map(question => question.responseMs);+ const sorted = [...latencies].sort((a, b) => a - b);+ const mid = Math.floor(sorted.length / 2);+ const medianMs = sorted.length ? (sorted.length % 2 ? sorted[mid] : Math.round((sorted[mid - 1] + sorted[mid]) / 2)) : null;+ const completion = totalCount ? questions.length / totalCount : null;+ return {+ score: accuracy == null ? 0 : Math.round(accuracy * (completion || 0) * 100),+ accuracy,+ completion,+ avgResponseMs: localAverageLatency(questions),+ medianMs,+ bestMs: sorted.length ? sorted[0] : null,+ answeredCount: latencies.length,+ totalCount,+ hits,+ omissions,+ falseAlarms,+ commissionErrors: falseAlarms,+ correctRejections,+ falseAlarmRate: noGoCount ? falseAlarms / noGoCount : null,+ latencyDistributionMs: latencies,+ };+}++export function localFlankerMetrics(questions, totalCount, refMs) {+ return {+ ...localExecutiveMetrics(questions, totalCount, refMs),+ congruencyCostMs: localCost(questions, question => !question.congruent, question => question.congruent),+ congruentAccuracy: localGroupAccuracy(questions, question => question.congruent),+ incongruentAccuracy: localGroupAccuracy(questions, question => !question.congruent),+ };+}+// Renders a `[x, y]` cell list (mental-rotation shapes) as a small filled-cell// grid within a `size x size` box — no images/canvas, just CSS grid squares.function ShapeGrid({ cells, size = 4, cellPx = 14 }) {@@ -336,11 +459,17 @@ export function buildCognitiveResult({ type, drill, questions, totalMs }) {// results screen doesn't show a number that jumps on save. Other types keep// the raw-accuracy approximation (server adds only a small speed bonus).const schulteMetrics = type === 'schulte-table' ? localSchulteMetrics(drill, questions) : null;+ const plannedTrials = drill.trials?.length || questions.length;+ const executiveMetrics = type === 'task-switching'+ ? localTaskSwitchMetrics(questions, plannedTrials, drill.config?.responseDeadlineMs || 2200)+ : type === 'go-no-go'+ ? localGoNoGoMetrics(questions, plannedTrials)+ : type === 'flanker' ? localFlankerMetrics(questions, plannedTrials, drill.config?.responseDeadlineMs || 1600) : null;const score = type === 'n-back'? localNBackScore(drill, questions): type === 'reaction-time'? localReactionTimeScore(drill, questions)- : schulteMetrics?.score ?? localAccuracyScore(questions);+ : executiveMetrics?.score ?? schulteMetrics?.score ?? localAccuracyScore(questions);return {module: 'cognitive',type,@@ -349,6 +478,7 @@ export function buildCognitiveResult({ type, drill, questions, totalMs }) {questions,score,...(schulteMetrics || {}),+ ...(executiveMetrics || {}),totalMs,};}@@ -456,6 +586,56 @@ export function scoreSchulteClick({ target, value, responseMs }) {};}+const TASK_SWITCH_VALUES = {+ color: ['blue', 'orange'],+ shape: ['circle', 'triangle'],+ fill: ['solid', 'outline'],+};++export function scoreTaskSwitchTrial({ trial, index, answer, responseMs }) {+ const values = TASK_SWITCH_VALUES[trial?.rule] || [];+ const valueIndex = values.indexOf(trial?.stimulus?.[trial?.rule]);+ const expected = valueIndex === 0 ? 'left' : valueIndex === 1 ? 'right' : null;+ return {+ prompt: trial?.rule || '',+ index,+ expected,+ answered: answer,+ correct: expected != null && answer === expected,+ responseMs,+ rule: trial?.rule,+ switched: trial?.switched === true,+ incongruent: trial?.incongruent === true,+ };+}++export function scoreGoNoGoTrial({ trial, index, pressed, responseMs }) {+ const noGo = trial?.kind === 'no-go';+ const answered = pressed ? 'go' : null;+ return {+ prompt: trial?.symbol || '',+ index,+ expected: noGo ? 'withhold' : 'go',+ answered,+ correct: noGo ? answered == null : answered === 'go',+ responseMs,+ noGo,+ };+}++export function scoreFlankerTrial({ trial, index, answer, responseMs }) {+ const expected = trial?.target === 'left' || trial?.target === 'right' ? trial.target : null;+ return {+ prompt: `${trial?.flanker || ''}-${trial?.target || ''}`,+ index,+ expected,+ answered: answer,+ correct: expected != null && answer === expected,+ responseMs,+ congruent: trial?.congruent === true,+ };+}+// =============================================================================// N-BACK — a letter stream; signal when the current letter matches N steps back// =============================================================================@@ -1276,3 +1456,276 @@ function ReactionTimeRunner({ drill, drillIndex, drillCount, onComplete, isTrain</div>);}++// =============================================================================+// EXECUTIVE CONTROL — shared binary-choice timing shell+// =============================================================================+function BinaryChoiceRunner({ type, drill, drillIndex, drillCount, onComplete, isTraining }) {+ const trials = drill.trials || [];+ const cueDelayMs = type === 'task-switching' ? (drill.config?.cueStimulusIntervalMs || 700) : 0;+ const deadlineMs = drill.config?.responseDeadlineMs || 1800;+ const [trialIdx, setTrialIdx] = useState(0);+ const [phase, setPhase] = useState(cueDelayMs ? 'cue' : 'stimulus');+ const [feedback, setFeedback] = useState(null);+ const questionsRef = useRef([]);+ const stimulusStartRef = useRef(0);+ const startedAtRef = useRef(Date.now());+ const acceptingRef = useRef(false);+ const cueTimerRef = useRef(null);+ const deadlineTimerRef = useRef(null);+ const advanceTimerRef = useRef(null);+ const finishedRef = useRef(false);+ const mountedRef = useMounted();++ const finish = useCallback(() => {+ if (finishedRef.current) return;+ finishedRef.current = true;+ onComplete(buildCognitiveResult({ type, drill, questions: questionsRef.current, totalMs: Date.now() - startedAtRef.current }));+ }, [type, drill, onComplete]);+ const finishRef = useRef(finish);+ finishRef.current = finish;++ const recordAnswer = useCallback((answer) => {+ if (!acceptingRef.current) return;+ acceptingRef.current = false;+ clearTimeout(deadlineTimerRef.current);+ const trial = trials[trialIdx];+ const responseMs = stimulusStartRef.current ? Date.now() - stimulusStartRef.current : deadlineMs;+ const question = type === 'task-switching'+ ? scoreTaskSwitchTrial({ trial, index: trialIdx, answer, responseMs })+ : scoreFlankerTrial({ trial, index: trialIdx, answer, responseMs });+ questionsRef.current.push(question);+ setFeedback(question.correct ? 'Correct' : answer == null ? 'Too slow' : `Center answer: ${question.expected}`);+ setPhase('feedback');+ const isLast = trialIdx + 1 >= trials.length;+ advanceTimerRef.current = setTimeout(() => {+ if (!mountedRef.current) return;+ if (isLast) finishRef.current(); else setTrialIdx(index => index + 1);+ }, isTraining ? 700 : 250);+ }, [deadlineMs, isTraining, trialIdx, trials, type]);+ const recordRef = useRef(recordAnswer);+ recordRef.current = recordAnswer;++ useEffect(() => {+ if (trialIdx >= trials.length) { finishRef.current(); return undefined; }+ acceptingRef.current = false;+ setFeedback(null);+ setPhase(cueDelayMs ? 'cue' : 'stimulus');+ const reveal = () => {+ if (!mountedRef.current) return;+ stimulusStartRef.current = Date.now();+ acceptingRef.current = true;+ setPhase('stimulus');+ deadlineTimerRef.current = setTimeout(() => recordRef.current(null), deadlineMs);+ };+ if (cueDelayMs) cueTimerRef.current = setTimeout(reveal, cueDelayMs);+ else reveal();+ return () => {+ acceptingRef.current = false;+ clearTimeout(cueTimerRef.current);+ clearTimeout(deadlineTimerRef.current);+ clearTimeout(advanceTimerRef.current);+ };+ }, [cueDelayMs, deadlineMs, trialIdx, trials]);++ useEffect(() => {+ const onKey = (event) => {+ if (phase !== 'stimulus') return;+ if (event.key === 'ArrowLeft' || event.key.toLowerCase() === 'a') {+ event.preventDefault();+ recordRef.current('left');+ } else if (event.key === 'ArrowRight' || event.key.toLowerCase() === 'd') {+ event.preventDefault();+ recordRef.current('right');+ }+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [phase]);++ const trial = trials[trialIdx];+ const activeRule = drill.rules?.find(rule => rule.id === trial?.rule);+ const leftLabel = type === 'task-switching' ? activeRule?.values?.[0] || 'Left' : 'Left';+ const rightLabel = type === 'task-switching' ? activeRule?.values?.[1] || 'Right' : 'Right';+ const shape = trial?.stimulus?.shape === 'triangle'+ ? (trial?.stimulus?.fill === 'outline' ? '△' : '▲')+ : (trial?.stimulus?.fill === 'outline' ? '○' : '●');+ const flankerCount = Math.max(1, drill.config?.flankerStrength || 2);+ const arrow = direction => direction === 'left' ? '←' : '→';+ const progressPct = trials.length ? (trialIdx / trials.length) * 100 : 0;++ return (+ <div className="max-w-lg mx-auto space-y-6">+ <DrillHeader type={type} isTraining={isTraining} drillIndex={drillIndex} drillCount={drillCount} />+ <p className="text-center text-sm text-gray-400">+ {type === 'task-switching'+ ? <>Use the <span className="text-white font-medium">cued rule</span>; ignore the other attributes.</>+ : <>Answer the direction of the <span className="text-white font-medium">center arrow</span>; ignore the flankers.</>}+ </p>++ <div className="min-h-[11rem] flex flex-col items-center justify-center gap-5" role="status" aria-live="polite">+ {type === 'task-switching' && (+ <div className="rounded-full border border-rose-500/40 bg-rose-500/10 px-5 py-2 text-sm font-semibold uppercase tracking-wider text-rose-200">+ Rule: {trial?.rule || '—'}+ </div>+ )}+ {phase === 'cue' && <div className="text-gray-500">Get ready…</div>}+ {phase === 'stimulus' && type === 'task-switching' && trial && (+ <div+ aria-label={`${trial.stimulus.color} ${trial.stimulus.fill} ${trial.stimulus.shape}`}+ className="text-8xl leading-none motion-reduce:transition-none"+ style={{ color: trial.stimulus.color === 'blue' ? '#3b82f6' : '#f97316' }}+ >+ {shape}+ </div>+ )}+ {phase === 'stimulus' && type === 'flanker' && trial && (+ <div+ aria-label={`Center arrow ${trial.target}`}+ className="flex items-center font-mono text-5xl text-white motion-reduce:transition-none"+ style={{ gap: `${Math.max(0.2, (drill.config?.flankerDistance || 2) * 0.3)}rem` }}+ >+ <span className="text-gray-500" aria-hidden="true">{arrow(trial.flanker).repeat(flankerCount)}</span>+ <span>{arrow(trial.target)}</span>+ <span className="text-gray-500" aria-hidden="true">{arrow(trial.flanker).repeat(flankerCount)}</span>+ </div>+ )}+ {phase === 'feedback' && (+ <div className={feedback === 'Correct' ? 'text-port-success' : 'text-port-error'}>{feedback}</div>+ )}+ </div>++ <div className="grid grid-cols-2 gap-3">+ <button type="button" onClick={() => recordRef.current('left')} disabled={phase !== 'stimulus'} className="px-5 py-4 rounded-lg border border-port-border bg-port-card hover:bg-port-bg disabled:opacity-40 text-white font-medium">+ ← {leftLabel}+ </button>+ <button type="button" onClick={() => recordRef.current('right')} disabled={phase !== 'stimulus'} className="px-5 py-4 rounded-lg border border-port-border bg-port-card hover:bg-port-bg disabled:opacity-40 text-white font-medium">+ {rightLabel} →+ </button>+ </div>++ <div className="space-y-1">+ <div className="flex justify-between text-xs text-gray-500"><span>Trial {Math.min(trialIdx + 1, trials.length)} of {trials.length}</span><span>{Math.round(progressPct)}%</span></div>+ <div className="w-full h-1.5 bg-port-border rounded-full overflow-hidden"><div className="h-full bg-rose-400/60 transition-all motion-reduce:transition-none" style={{ width: `${progressPct}%` }} /></div>+ </div>+ </div>+ );+}++function TaskSwitchingRunner(props) {+ return <BinaryChoiceRunner type="task-switching" {...props} />;+}++function FlankerRunner(props) {+ return <BinaryChoiceRunner type="flanker" {...props} />;+}++// =============================================================================+// GO / NO-GO — press for go, withhold through the deadline for no-go+// =============================================================================+function GoNoGoRunner({ drill, drillIndex, drillCount, onComplete, isTraining }) {+ const trials = drill.trials || [];+ const stimulusMs = drill.config?.stimulusMs || 600;+ const deadlineMs = drill.config?.responseDeadlineMs || 1400;+ const [trialIdx, setTrialIdx] = useState(0);+ const [visible, setVisible] = useState(true);+ const [feedback, setFeedback] = useState(null);+ const [accepting, setAccepting] = useState(true);+ const questionsRef = useRef([]);+ const trialStartRef = useRef(Date.now());+ const startedAtRef = useRef(Date.now());+ const acceptingRef = useRef(false);+ const hideTimerRef = useRef(null);+ const deadlineTimerRef = useRef(null);+ const advanceTimerRef = useRef(null);+ const finishedRef = useRef(false);+ const mountedRef = useMounted();++ const finish = useCallback(() => {+ if (finishedRef.current) return;+ finishedRef.current = true;+ onComplete(buildCognitiveResult({ type: 'go-no-go', drill, questions: questionsRef.current, totalMs: Date.now() - startedAtRef.current }));+ }, [drill, onComplete]);+ const finishRef = useRef(finish);+ finishRef.current = finish;++ const record = useCallback((pressed) => {+ if (!acceptingRef.current) return;+ acceptingRef.current = false;+ setAccepting(false);+ clearTimeout(hideTimerRef.current);+ clearTimeout(deadlineTimerRef.current);+ const question = scoreGoNoGoTrial({+ trial: trials[trialIdx],+ index: trialIdx,+ pressed,+ responseMs: pressed ? Date.now() - trialStartRef.current : deadlineMs,+ });+ questionsRef.current.push(question);+ setFeedback(question.correct ? (pressed ? 'Go' : 'Held') : pressed ? 'No-go lure' : 'Missed go signal');+ setVisible(false);+ const isLast = trialIdx + 1 >= trials.length;+ advanceTimerRef.current = setTimeout(() => {+ if (!mountedRef.current) return;+ if (isLast) finishRef.current(); else setTrialIdx(index => index + 1);+ }, isTraining ? 700 : 250);+ }, [deadlineMs, isTraining, trialIdx, trials]);+ const recordRef = useRef(record);+ recordRef.current = record;++ useEffect(() => {+ if (trialIdx >= trials.length) { finishRef.current(); return undefined; }+ acceptingRef.current = true;+ setAccepting(true);+ trialStartRef.current = Date.now();+ setVisible(true);+ setFeedback(null);+ hideTimerRef.current = setTimeout(() => {+ if (mountedRef.current) setVisible(false);+ }, stimulusMs);+ deadlineTimerRef.current = setTimeout(() => recordRef.current(false), deadlineMs);+ return () => {+ acceptingRef.current = false;+ clearTimeout(hideTimerRef.current);+ clearTimeout(deadlineTimerRef.current);+ clearTimeout(advanceTimerRef.current);+ };+ }, [deadlineMs, stimulusMs, trialIdx, trials]);++ useEffect(() => {+ const onKey = (event) => {+ if (event.code === 'Space' || event.key === ' ' || event.key === 'Enter') {+ event.preventDefault();+ recordRef.current(true);+ }+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, []);++ const trial = trials[trialIdx];+ const toneClass = trial?.tone === 'red' ? 'text-port-error' : trial?.tone === 'amber' ? 'text-port-warning' : 'text-port-success';+ const progressPct = trials.length ? (trialIdx / trials.length) * 100 : 0;+ return (+ <div className="max-w-lg mx-auto space-y-6">+ <DrillHeader type="go-no-go" isTraining={isTraining} drillIndex={drillIndex} drillCount={drillCount} />+ <p className="text-center text-sm text-gray-400">Press for <span className="text-port-success font-medium">green go</span>. Withhold for red or amber no-go lures.</p>+ <button+ type="button"+ aria-label={trial?.kind === 'no-go' ? 'No-go lure — withhold' : 'Go signal — respond'}+ onClick={() => recordRef.current(true)}+ disabled={!accepting}+ className="mx-auto w-48 h-48 rounded-2xl border border-port-border bg-port-card flex items-center justify-center disabled:opacity-70 motion-reduce:transition-none"+ >+ <span role="status" aria-live="polite" className={`text-8xl ${visible ? toneClass : 'text-transparent'}`}>+ {visible ? trial?.symbol : '·'}+ </span>+ </button>+ <div className={`text-center min-h-6 ${feedback && !questionsRef.current.at(-1)?.correct ? 'text-port-error' : 'text-port-success'}`} role="status" aria-live="polite">{feedback || 'Ready'}</div>+ <div className="space-y-1">+ <div className="flex justify-between text-xs text-gray-500"><span>Trial {Math.min(trialIdx + 1, trials.length)} of {trials.length}</span><span>{Math.round(progressPct)}%</span></div>+ <div className="w-full h-1.5 bg-port-border rounded-full overflow-hidden"><div className="h-full bg-rose-400/60 transition-all motion-reduce:transition-none" style={{ width: `${progressPct}%` }} /></div>+ </div>+ </div>+ );+}diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsxindex 9602bd55c9..6e882249de 100644--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx@@ -9,6 +9,12 @@ import PostCognitiveDrillRunner, {scoreStroopTrial,scoreMentalRotationTrial,scoreSchulteClick,+ scoreTaskSwitchTrial,+ scoreGoNoGoTrial,+ scoreFlankerTrial,+ localTaskSwitchMetrics,+ localGoNoGoMetrics,+ localFlankerMetrics,getDrillTutorial,hasSeenDrillTutorial,markDrillTutorialSeen,@@ -305,6 +311,81 @@ describe('scoreSchulteClick', () => {});});+describe('executive-control result builders', () => {+ it('task switching grades by the active rule and records switch cost', () => {+ const repeat = scoreTaskSwitchTrial({+ trial: { rule: 'color', stimulus: { color: 'blue', shape: 'triangle' }, switched: false, incongruent: true },+ index: 0,+ answer: 'left',+ responseMs: 300,+ });+ const switched = scoreTaskSwitchTrial({+ trial: { rule: 'shape', stimulus: { color: 'blue', shape: 'triangle' }, switched: true, incongruent: true },+ index: 1,+ answer: 'right',+ responseMs: 700,+ });+ expect(repeat.correct).toBe(true);+ expect(switched.correct).toBe(true);+ expect(localTaskSwitchMetrics([repeat, switched])).toMatchObject({+ accuracy: 1,+ switchCostMs: 400,+ switchAccuracy: 1,+ repeatAccuracy: 1,+ omissions: 0,+ });+ });++ it('go/no-go distinguishes omissions from false alarms', () => {+ const hit = scoreGoNoGoTrial({ trial: { kind: 'go', symbol: '●' }, index: 0, pressed: true, responseMs: 250 });+ const omission = scoreGoNoGoTrial({ trial: { kind: 'go', symbol: '●' }, index: 1, pressed: false, responseMs: 1000 });+ const falseAlarm = scoreGoNoGoTrial({ trial: { kind: 'no-go', symbol: '■' }, index: 2, pressed: true, responseMs: 200 });+ const rejection = scoreGoNoGoTrial({ trial: { kind: 'no-go', symbol: '■' }, index: 3, pressed: false, responseMs: 1000 });+ expect(localGoNoGoMetrics([hit, omission, falseAlarm, rejection])).toMatchObject({+ accuracy: 0.5,+ hits: 1,+ omissions: 1,+ falseAlarms: 1,+ commissionErrors: 1,+ correctRejections: 1,+ falseAlarmRate: 0.5,+ });+ });++ it('flanker grades the center arrow and records congruency cost', () => {+ const congruent = scoreFlankerTrial({ trial: { target: 'left', flanker: 'left', congruent: true }, index: 0, answer: 'left', responseMs: 300 });+ const incongruent = scoreFlankerTrial({ trial: { target: 'right', flanker: 'left', congruent: false }, index: 1, answer: 'right', responseMs: 650 });+ expect(localFlankerMetrics([congruent, incongruent])).toMatchObject({ accuracy: 1, congruencyCostMs: 350, congruentAccuracy: 1, incongruentAccuracy: 1 });+ });++ it('buildCognitiveResult carries task-specific measures into the unified result', () => {+ const questions = [+ scoreFlankerTrial({ trial: { target: 'left', flanker: 'left', congruent: true }, index: 0, answer: 'left', responseMs: 300 }),+ scoreFlankerTrial({ trial: { target: 'right', flanker: 'left', congruent: false }, index: 1, answer: 'right', responseMs: 600 }),+ ];+ const result = buildCognitiveResult({ type: 'flanker', drill: { type: 'flanker', config: {} }, questions, totalMs: 900 });+ expect(result).toMatchObject({ module: 'cognitive', type: 'flanker', accuracy: 1, congruencyCostMs: 300, totalMs: 900 });+ expect(result.latencyDistributionMs).toEqual([300, 600]);+ });++ it('keeps a partial executive result completion-aware', () => {+ const question = scoreFlankerTrial({+ trial: { target: 'left', flanker: 'right', congruent: false },+ index: 0,+ answer: 'left',+ responseMs: 300,+ });+ const result = buildCognitiveResult({+ type: 'flanker',+ drill: { type: 'flanker', config: { responseDeadlineMs: 1500 }, trials: Array.from({ length: 4 }, () => ({})) },+ questions: [question],+ totalMs: 300,+ });+ expect(result).toMatchObject({ accuracy: 1, completion: 0.25, totalCount: 4 });+ expect(result.score).toBeLessThan(25);+ });+});+describe('SchulteTableRunner error recording', () => {beforeEach(() => {vi.useFakeTimers();@@ -584,3 +665,93 @@ describe('first-run tutorial gate', () => {expect(screen.getByRole('button', { name: /wait for the signal/i })).toBeInTheDocument();});});++describe('executive-control runners', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ markDrillTutorialSeen('task-switching');+ markDrillTutorialSeen('go-no-go');+ markDrillTutorialSeen('flanker');+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('task switching supports keyboard answers, visible instructions, and accessible live state', () => {+ const onComplete = vi.fn();+ render(<PostCognitiveDrillRunner+ drill={{+ type: 'task-switching',+ config: { cueStimulusIntervalMs: 100, responseDeadlineMs: 1000 },+ rules: [{ id: 'color', values: ['blue', 'orange'] }, { id: 'shape', values: ['circle', 'triangle'] }],+ trials: [{ rule: 'color', stimulus: { color: 'blue', shape: 'triangle', fill: 'solid' }, switched: false, incongruent: true }],+ }}+ drillIndex={0}+ drillCount={1}+ onComplete={onComplete}+ isTraining={false}+ />);+ expect(screen.getByText(/cued rule/i)).toBeInTheDocument();+ expect(screen.getAllByRole('status').length).toBeGreaterThan(0);+ act(() => vi.advanceTimersByTime(100));+ fireEvent.keyDown(window, { key: 'ArrowLeft' });+ act(() => vi.advanceTimersByTime(250));+ expect(onComplete).toHaveBeenCalledTimes(1);+ expect(onComplete.mock.calls[0][0]).toMatchObject({ type: 'task-switching', accuracy: 1, omissions: 0 });+ });++ it('go/no-go supports touch, advances withheld trials at the deadline, and records errors separately', () => {+ const onComplete = vi.fn();+ render(<PostCognitiveDrillRunner+ drill={{+ type: 'go-no-go',+ config: { stimulusMs: 100, responseDeadlineMs: 500 },+ trials: [{ kind: 'go', symbol: '●', tone: 'green' }, { kind: 'no-go', symbol: '■', tone: 'red' }],+ }}+ drillIndex={0}+ drillCount={1}+ onComplete={onComplete}+ isTraining={false}+ />);+ fireEvent.click(screen.getByRole('button', { name: /go signal.*respond/i }));+ act(() => vi.advanceTimersByTime(251));+ expect(screen.getByRole('button', { name: /no-go lure.*withhold/i })).toBeInTheDocument();+ act(() => vi.advanceTimersByTime(501));+ act(() => vi.advanceTimersByTime(251));+ expect(onComplete).toHaveBeenCalledTimes(1);+ expect(onComplete.mock.calls[0][0]).toMatchObject({ hits: 1, correctRejections: 1, falseAlarms: 0, omissions: 0, accuracy: 1 });+ });++ it('flanker supports touch controls and ignores the distractor direction', () => {+ const onComplete = vi.fn();+ render(<PostCognitiveDrillRunner+ drill={{ type: 'flanker', config: { responseDeadlineMs: 800, flankerDistance: 1, flankerStrength: 3 }, trials: [{ target: 'right', flanker: 'left', congruent: false }] }}+ drillIndex={0}+ drillCount={1}+ onComplete={onComplete}+ isTraining={false}+ />);+ fireEvent.click(screen.getByRole('button', { name: /right/i }));+ act(() => vi.advanceTimersByTime(250));+ expect(onComplete).toHaveBeenCalledTimes(1);+ expect(onComplete.mock.calls[0][0]).toMatchObject({ type: 'flanker', accuracy: 1, incongruentAccuracy: 1 });+ });++ it('cleans timers on early exit and can restart the same drill cleanly on resume', () => {+ const drill = { type: 'go-no-go', config: { stimulusMs: 200, responseDeadlineMs: 800 }, trials: [{ kind: 'go', symbol: '●', tone: 'green' }] };+ const abandoned = vi.fn();+ const first = render(<PostCognitiveDrillRunner drill={drill} drillIndex={0} drillCount={1} onComplete={abandoned} isTraining={false} />);+ first.unmount();+ act(() => vi.advanceTimersByTime(2000));+ expect(abandoned).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);++ const resumed = vi.fn();+ render(<PostCognitiveDrillRunner drill={drill} drillIndex={0} drillCount={1} onComplete={resumed} isTraining={false} />);+ fireEvent.keyDown(window, { code: 'Space', key: ' ' });+ act(() => vi.advanceTimersByTime(250));+ expect(resumed).toHaveBeenCalledTimes(1);+ expect(resumed.mock.calls[0][0].questions).toHaveLength(1);+ });+});diff --git a/client/src/components/meatspace/post/PostDrillConfig.jsx b/client/src/components/meatspace/post/PostDrillConfig.jsxindex 934f5f09e1..719b15e953 100644--- a/client/src/components/meatspace/post/PostDrillConfig.jsx+++ b/client/src/components/meatspace/post/PostDrillConfig.jsx@@ -255,12 +255,58 @@ const COGNITIVE_DRILL_META = {],defaults: { enabled: true, mode: 'simple', count: 15, minDelayMs: 1000, maxDelayMs: 3000, choices: 3 },},+ 'task-switching': {+ label: 'Task Switching',+ desc: 'Apply the currently cued rule — focused practice for switching between explicit classifications',+ progressive: true,+ ladderFields: ['ruleCount', 'switchRatePct', 'cueStimulusIntervalMs', 'incongruentPct', 'responseDeadlineMs'],+ fields: [+ { key: 'count', label: 'Trials', type: 'number', min: 6, max: 50 },+ { key: 'ruleCount', label: 'Rules', type: 'number', min: 2, max: 3 },+ { key: 'switchRatePct', label: 'Switch Trials (%)', type: 'number', min: 0, max: 100 },+ { key: 'cueStimulusIntervalMs', label: 'Cue Lead (ms)', type: 'number', min: 100, max: 2000 },+ { key: 'incongruentPct', label: 'Conflicting Stimuli (%)', type: 'number', min: 0, max: 100 },+ { key: 'responseDeadlineMs', label: 'Response Deadline (ms)', type: 'number', min: 500, max: 5000 },+ ],+ defaults: { enabled: false, progressive: true, count: 18, ruleCount: 2, switchRatePct: 50, cueStimulusIntervalMs: 700, incongruentPct: 50, responseDeadlineMs: 2200 },+ },+ 'go-no-go': {+ label: 'Go / No-Go',+ desc: 'Respond to go signals and withhold to lures — focused response-inhibition practice',+ progressive: true,+ ladderFields: ['noGoPct', 'stimulusMs', 'lureSimilarity', 'responseDeadlineMs'],+ fields: [+ { key: 'count', label: 'Trials', type: 'number', min: 6, max: 60 },+ { key: 'noGoPct', label: 'No-Go Trials (%)', type: 'number', min: 5, max: 80 },+ { key: 'stimulusMs', label: 'Stimulus (ms)', type: 'number', min: 100, max: 2000 },+ { key: 'lureSimilarity', label: 'Lure Similarity', type: 'select', options: [+ { value: 'low', label: 'Low' },+ { value: 'high', label: 'High' },+ ] },+ { key: 'responseDeadlineMs', label: 'Response Deadline (ms)', type: 'number', min: 500, max: 5000 },+ ],+ defaults: { enabled: false, progressive: true, count: 20, noGoPct: 25, stimulusMs: 600, lureSimilarity: 'low', responseDeadlineMs: 1400 },+ },+ 'flanker': {+ label: 'Flanker Control',+ desc: 'Report the center arrow while ignoring surrounding arrows — narrow interference-control practice',+ progressive: true,+ ladderFields: ['congruentPct', 'flankerDistance', 'flankerStrength', 'responseDeadlineMs'],+ fields: [+ { key: 'count', label: 'Trials', type: 'number', min: 6, max: 60 },+ { key: 'congruentPct', label: 'Congruent Trials (%)', type: 'number', min: 0, max: 100 },+ { key: 'flankerDistance', label: 'Flanker Distance', type: 'number', min: 1, max: 4 },+ { key: 'flankerStrength', label: 'Flanker Strength', type: 'number', min: 1, max: 3 },+ { key: 'responseDeadlineMs', label: 'Response Deadline (ms)', type: 'number', min: 500, max: 5000 },+ ],+ defaults: { enabled: false, progressive: true, count: 20, congruentPct: 60, flankerDistance: 2, flankerStrength: 2, responseDeadlineMs: 1600 },+ },};const COGNITIVE_TYPES = Object.keys(COGNITIVE_DRILL_META);// String-valued cognitive config keys must NOT be coerced to Number on edit.-const COGNITIVE_STRING_FIELDS = new Set(['direction', 'mode']);+const COGNITIVE_STRING_FIELDS = new Set(['direction', 'mode', 'lureSimilarity']);// Seed every cognitive drill type so a card's toggle reflects real, persistable// state — same enabled-by-presence convention as seedLlmDrillTypes.diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsxindex eb25bbb7de..5c6314f946 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx@@ -64,6 +64,9 @@ export function cognitiveSummary(type, cfg) {if (type === 'stroop') return `${cfg.incongruentPct ?? 75}% conflict`;if (type === 'mental-rotation') return `${cfg.optionCount ?? 4} options`;if (type === 'reaction-time') return `${cfg.count ?? 15} trials (${cfg.mode ?? 'simple'})`;+ if (type === 'task-switching') return `${cfg.ruleCount ?? 2} rules · ${cfg.switchRatePct ?? 50}% switch`;+ if (type === 'go-no-go') return `${cfg.noGoPct ?? 25}% no-go · ${cfg.lureSimilarity ?? 'low'} similarity`;+ if (type === 'flanker') return `${100 - (cfg.congruentPct ?? 60)}% conflict · strength ${cfg.flankerStrength ?? 2}`;return cfg.count ? `${cfg.count} trials` : '';}@@ -277,6 +280,15 @@ export default function PostSessionLauncher({minDelayMs: cfg.minDelayMs,maxDelayMs: cfg.maxDelayMs,choices: cfg.choices,+ ruleCount: cfg.ruleCount,+ switchRatePct: cfg.switchRatePct,+ cueStimulusIntervalMs: cfg.cueStimulusIntervalMs,+ responseDeadlineMs: cfg.responseDeadlineMs,+ noGoPct: cfg.noGoPct,+ lureSimilarity: cfg.lureSimilarity,+ congruentPct: cfg.congruentPct,+ flankerDistance: cfg.flankerDistance,+ flankerStrength: cfg.flankerStrength,});// Composed sessions (Full POST / Quick) honor `sessionModules` (issue #2100):diff --git a/client/src/components/meatspace/post/PracticePlan.test.jsx b/client/src/components/meatspace/post/PracticePlan.test.jsxindex 8c1fe4bd57..1c70c6df88 100644--- a/client/src/components/meatspace/post/PracticePlan.test.jsx+++ b/client/src/components/meatspace/post/PracticePlan.test.jsx@@ -181,7 +181,7 @@ describe('PracticePlan save', () => {const [patch] = updatePostConfig.mock.calls[0];expect(Object.keys(patch.llmDrills.drillTypes)).toHaveLength(14);expect(Object.keys(patch.mentalMath.drillTypes)).toHaveLength(5);- expect(Object.keys(patch.cognitive.drillTypes)).toHaveLength(6);+ expect(Object.keys(patch.cognitive.drillTypes)).toHaveLength(9);expect(Object.keys(patch.memory.drillTypes)).toHaveLength(3);// A drill type absent from the saved config is persisted as disabled — the// launcher already ignored it, so seeding must not silently switch it on.diff --git a/client/src/components/meatspace/post/constants.js b/client/src/components/meatspace/post/constants.jsindex e12057bcb5..4d4c902d64 100644--- a/client/src/components/meatspace/post/constants.js+++ b/client/src/components/meatspace/post/constants.js@@ -7,7 +7,7 @@ export const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-flueexport const MEMORY_DRILL_TYPES = ['memory-fill-blank', 'memory-sequence', 'memory-element-flash'];// Deterministic cognitive drills (no LLM). Mirror the server's// COGNITIVE_DRILL_TYPES in server/services/meatspacePostCognitive.js.-export const COGNITIVE_DRILL_TYPES = ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time'];+export const COGNITIVE_DRILL_TYPES = ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time', 'task-switching', 'go-no-go', 'flanker'];// Drill types valid elsewhere but not yet wired into the interactive POST// session drill picker. Multi-blank fill-in-the-blank is now wired end to end,@@ -107,7 +107,7 @@ export const POST_TOPICS = [label: 'Cognitive',module: 'cognitive',surface: 'session',- drillTypes: ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time'],+ drillTypes: ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time', 'task-switching', 'go-no-go', 'flanker'],},{id: 'morse',@@ -291,6 +291,9 @@ export const DRILL_LABELS = {'schulte-table': 'Schulte Table','mental-rotation': 'Mental Rotation','reaction-time': 'Reaction Time',+ 'task-switching': 'Task Switching',+ 'go-no-go': 'Go / No-Go',+ 'flanker': 'Flanker Control',};// Human-readable label for a domain key. `other` collects drills whose typediff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.jsindex db8fb51390..b6b507ff45 100644--- a/client/src/hooks/usePostSession.js+++ b/client/src/hooks/usePostSession.js@@ -536,6 +536,7 @@ export function usePostSession() {questionCount,correctCount,latencyMs: r.totalMs || 0,+ ...(r.drillData ? { drillData: r.drillData } : {}),correct: questionCount > 0 ? correctCount === questionCount : null,score: r.score !== undefined ? r.score : (questionCount > 0 ? (correctCount / questionCount) * 100 : null),completion: r.completion !== undefined ? r.completion : (questionCount > 0 ? answeredCount / questionCount : null),@@ -543,6 +544,13 @@ export function usePostSession() {confidence: r.confidence ?? null,inputMode,scorerProvenance: isLlmDrill ? 'server-llm' : 'client-deterministic',+ ...Object.fromEntries([+ 'accuracy', 'avgResponseMs', 'answeredCount', 'totalCount', 'attemptCount', 'errorCount',+ 'medianMs', 'bestMs', 'span', 'hits', 'misses', 'omissions', 'commissionErrors',+ 'falseAlarms', 'correctRejections', 'switchCostMs', 'switchAccuracy', 'repeatAccuracy',+ 'congruencyCostMs', 'congruentAccuracy', 'incongruentAccuracy', 'falseAlarmRate',+ 'latencyDistributionMs',+ ].filter(key => r[key] !== undefined).map(key => [key, r[key]])),...((questions || Array.isArray(r.questions)) ? { questions: questions || r.questions } : {}),};});diff --git a/client/src/hooks/usePostSession.test.js b/client/src/hooks/usePostSession.test.jsindex c6fa186369..29feb51d75 100644--- a/client/src/hooks/usePostSession.test.js+++ b/client/src/hooks/usePostSession.test.js@@ -644,6 +644,51 @@ describe('usePostSession — atomic training-run save (#4441)', () => {expect(retryPayload.attempts.map((attempt) => attempt.id)).toEqual(firstPayload.attempts.map((attempt) => attempt.id));});++ it('sends deterministic drill data and executive metrics for server-authoritative training rescoring', async () => {+ const drillData = {+ type: 'flanker',+ config: { seed: 'client-flanker', responseDeadlineMs: 1500 },+ trials: [{ target: 'right', flanker: 'left', congruent: false }],+ };+ generatePostDrill.mockResolvedValue(drillData);+ submitTrainingRun.mockResolvedValue({ id: 'training-run', attemptCount: 1 });+ const { result } = renderHook(() => usePostSession());+ await act(async () => {+ await result.current.startSession([{ type: 'flanker', config: {} }], true);+ });+ act(() => {+ result.current.completeCognitiveDrill({+ module: 'cognitive',+ type: 'flanker',+ config: drillData.config,+ drillData,+ questions: [{ index: 0, answered: 'right', correct: true, responseMs: 400, congruent: false }],+ score: 100,+ accuracy: 1,+ completion: 1,+ congruencyCostMs: null,+ incongruentAccuracy: 1,+ omissions: 0,+ commissionErrors: 0,+ latencyDistributionMs: [400],+ totalMs: 400,+ });+ });+ await act(async () => { await result.current.saveSession({}); });++ expect(submitTrainingRun.mock.calls[0][0].attempts[0]).toEqual(expect.objectContaining({+ drillType: 'flanker',+ drillData,+ accuracy: 1,+ congruencyCostMs: null,+ incongruentAccuracy: 1,+ omissions: 0,+ commissionErrors: 0,+ latencyDistributionMs: [400],+ scorerProvenance: 'client-deterministic',+ }));+ });});describe('usePostSession — LLM training-log per-question breakdown (issue #2114)', () => {diff --git a/docs/features/post.md b/docs/features/post.mdindex 34fc2e429b..22a677a163 100644--- a/docs/features/post.md+++ b/docs/features/post.md@@ -24,7 +24,15 @@ Memory Builder drills drawn from the user's memory items: `memory-sequence`, `me`what-if` (absurd hypotheticals), `alternative-uses` (divergent-thinking classic), `story-prompt` (micro-story from 3 random words), `invention-pitch`, `reframe` (recast a negative situation positively/humorously). LLM-scored for originality, elaboration, and feasibility.### Cognitive (~90s)-Classic psychometric drills, scored deterministically server-side (`server/services/meatspacePostCognitive.js`, runner `PostCognitiveDrillRunner.jsx`): `n-back`, `digit-span`, `stroop`, `schulte-table`, `mental-rotation`, `reaction-time`.+Focused cognitive-skill drills, scored deterministically server-side (`server/services/meatspacePostCognitive.js`, runner `PostCognitiveDrillRunner.jsx`): `n-back`, `digit-span`, `stroop`, `schulte-table`, `mental-rotation`, `reaction-time`, `task-switching`, `go-no-go`, and `flanker`.++The executive-control pack practices three narrow task skills; it is not a clinical assessment and makes no claim of generalized cognitive transfer:++- **Task Switching** applies a visible color/shape/fill rule, measuring switch cost and repeat-vs-switch accuracy. Its ladder changes rule count, switch rate, cue lead, conflicting attributes, and response deadline.+- **Go / No-Go** responds to go signals and withholds to no-go lures, measuring hits, omissions, false alarms/commission errors, correct rejections, and latency. Its ladder changes no-go frequency, stimulus duration, lure similarity, and deadline.+- **Flanker Control** reports a center arrow around agreeing or conflicting flankers, measuring congruency cost, congruent/incongruent accuracy, omissions, and latency. Its ladder changes congruency ratio, flanker distance/strength, and deadline.++Each generated executive-control drill carries a seed. The server regenerates its answer key from that seed and the validated difficulty config when saving either a scored session or an atomic training run; client-provided correctness and aggregate metrics are never authoritative.### Morse (training-only)`MorseTrainer.jsx` (`morse-copy`, `morse-head-copy`, `morse-send`, deep-linked at `/post/morse/:mode`) is deliberately excluded from scored sessions — Morse practice posts to the training log only.@@ -55,7 +63,7 @@ Configurable memory training for songs, poems, sequences, speeches, or any order## Scoring- **Math**: server-rescored — the server strips client-provided correctness and re-derives expected answers (`meatspacePost.js`, "never trust client-provided expected"); estimation compares within tolerance. Accuracy plus speed bonus.-- **Cognitive**: deterministic server-side rescoring per drill type.+- **Cognitive**: deterministic server-side rescoring per drill type. Executive-control attempts additionally retain switch/congruency cost, false alarms, omissions, commission errors, accuracy/completion, and the per-response latency distribution in the unified run/attempt record.- **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.diff --git a/server/lib/README.md b/server/lib/README.mdindex c27bc553fe..8d1fc424a1 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -306,7 +306,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `postAdaptive.js` | Pure POST adaptive-difficulty policy — nudges a math drill's primary knob (`steps`/`maxDigits`/`maxExponent`/`tolerancePct`) up/down within clamped bounds from recent scored performance. Opt-in via the config Adaptive toggle. || `postMultiplicationLadder.js` | Pure progressive multiplication ladder — mastery-gated difficulty rungs (`[1,1]` → `[1,2]` → `[1,1,1]` → …). Resolves the user's current level from per-level speed+accuracy stats so the plain multiplication drill ramps up instead of starting at a fixed hard difficulty. On by default. Built on `postProgression.js`. || `postPowersLadder.js` | Pure technique-anchored Powers ladder — cumulative named-method pools, full supported-pair registry, and speed+accuracy mastery progression built on `postProgression.js`. |-| `postProgression.js` | Generic mastery-gated progression ladder (extracted from `postMultiplicationLadder.js`) — `createProgression({ levels, describeLevel, speedTargetForLevel? })` resolves a user's current rung from exact-level sample, accuracy, completion, and optional speed evidence with an anti-demotion floor. Also defines meaningful cognitive-drill ladders (n-back / digit-span / Schulte / mental rotation / Stroop) and their level→generator-config mapping. |+| `postProgression.js` | Generic mastery-gated progression ladder (extracted from `postMultiplicationLadder.js`) — `createProgression({ levels, describeLevel, speedTargetForLevel? })` resolves a user's current rung from exact-level sample, accuracy, completion, and optional speed evidence with an anti-demotion floor. Also defines meaningful cognitive-drill ladders (including task switching, Go/No-Go, and Flanker) and their level→generator-config mapping. || `spacedRepetition.js` | The shared SM-2-inspired review scheduler, extracted from `services/meatspacePostMemory.js` when SongBook practice became its second consumer (#4102). One four-field schedule shape (`{ ease, intervalDays, nextReview, lastReviewed }`, no `repetitions` counter — the 0 → 1 → 6 → `round(prev * ease)` ladder derives from the previous interval, so a schedule round-trips through import/export/federation on those four fields alone). `advanceSchedule(schedule, ratio, now)` is the core (ease clamped to `MIN_EASE`..`MAX_EASE`, interval capped at `MAX_INTERVAL_DAYS` so `new Date(now + interval*DAY)` can't overflow into an Invalid Date; quality < 3 zeroes the interval to resurface the record but still applies the ease penalty). `mergeScheduleAdvance(prev, advanced, now)` gates interval GROWTH to once per review day (a shrink always applies) for UIs that submit per chunk/section; `isSameReviewDay` is that gate's own predicate, reusable by callers gating their own once-a-day progression. `scheduleOrDefault(record, schedule?)` is the read-path fallback — a record with no schedule derives one anchored to its `updatedAt`/`createdAt` (stable and in the past → due now), so "due" can't flap between two reads a millisecond apart. `ratioToQuality` / `qualityToRatio` are exact inverses over the integers, so a self-graded 0..5 review lands on the quality the user picked. `isScheduleDue` treats an absent/unparseable `nextReview` as due — a record we can't schedule is one to surface, never one to hide forever. Pure. || `songPractice.js` | SongBook repertoire practice scheduling (#4102) — the pure core behind `POST /api/brain/songbook/:id/practice`. `applySongPractice(song, quality, now)` → `{ stage, practice }`, the exact partial to hand `brainStorage.updateWith`: it advances the shared `spacedRepetition` schedule from a 0..5 self-grade and moves the song's `stage` along `SONG_STAGE_ORDER` (≥ `SONG_PROMOTE_MIN_QUALITY` promotes, ≤ `SONG_REGRESS_MAX_QUALITY` regresses, a 3 holds). Promotion is gated to once per practice day (regression never is), and a practiced song floors at `learning` — `new` means "never picked up", which stops being true after one session. `songPracticeOrDefault(song)` derives the schedule on READ for every song predating the feature (nothing is backfilled to disk: a migration would restamp `updatedAt` on every record and spray federation churn, and would break the `data.reference/` seeds' byte-identity). `nextSongStage` no-ops on a stage this install doesn't recognize, so a practice log can't rewrite a value synced from a newer peer. `isSongDue(song, now)` mirrors the client's `songDueAt` in `client/src/components/songbook/constants.js`. Pure. || `postTopics.js` | Pure POST practice-topic registry — `POST_TOPICS` (`{ id, label, module, surface, drillTypes }`) is the single source of truth for "what am I studying?", plus `resolveTopicForDrillType` / `isTopicEnabled` / `isMemoryItemEnabled`. Gates session composition and recommendations, including Memory's composed and dedicated practice routes plus standalone Morse. Mirrored to the client's post `constants.js` (parity test). |diff --git a/server/lib/postProgression.js b/server/lib/postProgression.jsindex 304a8fd029..fff83d3d35 100644--- a/server/lib/postProgression.js+++ b/server/lib/postProgression.js@@ -258,6 +258,42 @@ export const COGNITIVE_LADDERS = {describe: rung => `${rung.incongruentPct}% conflict · ${rung.count} trials`,speedTargetsMs: [1500, 1400, 1300, 1200],},+ // Executive rule switching: add a third rule, increase the proportion of+ // switches/conflicting attributes, shorten the cue lead, and tighten the+ // response window. Every rung changes at least two demand levers.+ 'task-switching': {+ levels: [+ { ruleCount: 2, switchRatePct: 25, cueStimulusIntervalMs: 900, incongruentPct: 30, responseDeadlineMs: 2500 },+ { ruleCount: 2, switchRatePct: 50, cueStimulusIntervalMs: 700, incongruentPct: 50, responseDeadlineMs: 2200 },+ { ruleCount: 3, switchRatePct: 45, cueStimulusIntervalMs: 550, incongruentPct: 65, responseDeadlineMs: 1900 },+ { ruleCount: 3, switchRatePct: 65, cueStimulusIntervalMs: 350, incongruentPct: 80, responseDeadlineMs: 1600 },+ ],+ describe: rung => `${rung.ruleCount} rules · ${rung.switchRatePct}% switches · ${rung.incongruentPct}% conflict`,+ speedTargetsMs: [1800, 1600, 1450, 1250],+ },+ // Response inhibition: no-go events become more frequent, the display and+ // deadline tighten, then lure similarity increases.+ 'go-no-go': {+ levels: [+ { noGoPct: 20, stimulusMs: 750, lureSimilarity: 'low', responseDeadlineMs: 1600 },+ { noGoPct: 30, stimulusMs: 600, lureSimilarity: 'low', responseDeadlineMs: 1400 },+ { noGoPct: 35, stimulusMs: 475, lureSimilarity: 'high', responseDeadlineMs: 1200 },+ { noGoPct: 40, stimulusMs: 350, lureSimilarity: 'high', responseDeadlineMs: 950 },+ ],+ describe: rung => `${rung.noGoPct}% no-go · ${rung.lureSimilarity} similarity · ${rung.responseDeadlineMs}ms`,+ },+ // Flanker interference: reduce the easy congruent share, bring distractors+ // closer, strengthen them, and tighten the response window.+ 'flanker': {+ levels: [+ { congruentPct: 75, flankerDistance: 4, flankerStrength: 1, responseDeadlineMs: 1900 },+ { congruentPct: 60, flankerDistance: 3, flankerStrength: 2, responseDeadlineMs: 1650 },+ { congruentPct: 50, flankerDistance: 2, flankerStrength: 2, responseDeadlineMs: 1400 },+ { congruentPct: 40, flankerDistance: 1, flankerStrength: 3, responseDeadlineMs: 1150 },+ ],+ describe: rung => `${100 - rung.congruentPct}% conflict · distance ${rung.flankerDistance} · strength ${rung.flankerStrength}`,+ speedTargetsMs: [1400, 1250, 1100, 950],+ },};// Laddered cognitive drill types (drives getCognitiveProgress + the config UI).diff --git a/server/lib/postProgression.test.js b/server/lib/postProgression.test.jsindex 59226e5f89..9be17baa87 100644--- a/server/lib/postProgression.test.js+++ b/server/lib/postProgression.test.js@@ -106,7 +106,7 @@ describe('PROGRESSION_MASTERY_DEFAULTS', () => {describe('cognitive ladders', () => {it('ladders exist for every skill drill but not reaction-time', () => {- expect(COGNITIVE_LADDER_TYPES).toEqual(['n-back', 'digit-span', 'schulte-table', 'mental-rotation', 'stroop']);+ expect(COGNITIVE_LADDER_TYPES).toEqual(['n-back', 'digit-span', 'schulte-table', 'mental-rotation', 'stroop', 'task-switching', 'go-no-go', 'flanker']);expect(cognitiveLadder('reaction-time')).toBeNull();expect(cognitiveLadder('nope')).toBeNull();});@@ -131,6 +131,23 @@ describe('cognitive ladders', () => {expect(rotation.map(r => r.optionCount)).toEqual([2, 3, 3, 4]);});+ it('executive-control ladders change multiple cognitive-demand levers beyond trial count', () => {+ const switching = COGNITIVE_LADDERS['task-switching'].levels;+ expect(switching.map(rung => rung.ruleCount)).toEqual([2, 2, 3, 3]);+ expect(switching.map(rung => rung.switchRatePct)).toEqual([25, 50, 45, 65]);+ expect(switching.map(rung => rung.cueStimulusIntervalMs)).toEqual([900, 700, 550, 350]);++ const inhibition = COGNITIVE_LADDERS['go-no-go'].levels;+ expect(inhibition.map(rung => rung.noGoPct)).toEqual([20, 30, 35, 40]);+ expect(inhibition.map(rung => rung.lureSimilarity)).toEqual(['low', 'low', 'high', 'high']);+ expect(inhibition.map(rung => rung.stimulusMs)).toEqual([750, 600, 475, 350]);++ const flanker = COGNITIVE_LADDERS.flanker.levels;+ expect(flanker.map(rung => rung.congruentPct)).toEqual([75, 60, 50, 40]);+ expect(flanker.map(rung => rung.flankerDistance)).toEqual([4, 3, 2, 1]);+ expect(flanker.map(rung => rung.flankerStrength)).toEqual([1, 2, 2, 3]);+ });+it('cognitiveLevelConfig returns the clamped rung knobs (a fresh copy)', () => {expect(cognitiveLevelConfig('n-back', 0)).toEqual({ n: 1, stimulusMs: 2500 });expect(cognitiveLevelConfig('n-back', 99)).toEqual({ n: 3, stimulusMs: 1600 });diff --git a/server/lib/postTopics.js b/server/lib/postTopics.jsindex 944eb434a2..cd6daa8f48 100644--- a/server/lib/postTopics.js+++ b/server/lib/postTopics.js@@ -73,7 +73,7 @@ export const POST_TOPICS = [label: 'Cognitive',module: 'cognitive',surface: 'session',- drillTypes: ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time'],+ drillTypes: ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time', 'task-switching', 'go-no-go', 'flanker'],},{// Morse is deliberately outside POST_MODULES (it posts through the separate,diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex f099ce9ffd..c96a796a13 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -46,6 +46,14 @@ const questionResultSchema = z.object({// Reaction-time drill only: player pressed before the stimulus appeared.// Always scored wrong server-side regardless of any client-supplied correct.falseStart: z.boolean().optional(),+ // Executive-control drill evidence. These are server-recomputed from the+ // seeded generated trial, but remain in the stored per-question record so+ // progress/history can explain switch and congruency costs.+ rule: z.enum(['color', 'shape', 'fill']).optional(),+ switched: z.boolean().optional(),+ incongruent: z.boolean().optional(),+ congruent: z.boolean().optional(),+ noGo: z.boolean().optional(),// Memory drill questions only: which chunk (memory-sequence) / element// (memory-element-flash) this answer attributes to, so submitPostSession can// merge per-chunk/per-element mastery (mergeMasteryFromSession in@@ -167,7 +175,17 @@ const drillTypeConfigSchema = z.object({mode: z.enum(['simple', 'choice']).optional(),minDelayMs: z.number().int().min(300).max(5000).optional(),maxDelayMs: z.number().int().min(300).max(8000).optional(),- choices: z.number().int().min(2).max(4).optional()+ choices: z.number().int().min(2).max(4).optional(),+ seed: z.string().max(100).optional(),+ ruleCount: z.number().int().min(2).max(3).optional(),+ switchRatePct: z.number().int().min(0).max(100).optional(),+ cueStimulusIntervalMs: z.number().int().min(100).max(2000).optional(),+ responseDeadlineMs: z.number().int().min(500).max(5000).optional(),+ noGoPct: z.number().int().min(5).max(80).optional(),+ lureSimilarity: z.enum(['low', 'high']).optional(),+ congruentPct: z.number().int().min(0).max(100).optional(),+ flankerDistance: z.number().int().min(1).max(4).optional(),+ flankerStrength: z.number().int().min(1).max(3).optional(),});// Task result within a session@@ -209,6 +227,16 @@ const taskResultSchema = z.object({misses: z.number().int().min(0).optional(),falseAlarms: z.number().int().min(0).optional(),correctRejections: z.number().int().min(0).optional(),+ omissions: z.number().int().min(0).optional(),+ commissionErrors: z.number().int().min(0).optional(),+ switchCostMs: z.number().nullable().optional(),+ switchAccuracy: z.number().min(0).max(1).nullable().optional(),+ repeatAccuracy: z.number().min(0).max(1).nullable().optional(),+ congruencyCostMs: z.number().nullable().optional(),+ congruentAccuracy: z.number().min(0).max(1).nullable().optional(),+ incongruentAccuracy: z.number().min(0).max(1).nullable().optional(),+ falseAlarmRate: z.number().min(0).max(1).nullable().optional(),+ latencyDistributionMs: z.array(z.number().min(0)).max(500).optional(),hintUsed: z.boolean().optional(),confidence: z.number().min(0).max(1).nullable().optional(),inputMode: z.string().min(1).max(50).optional(),@@ -622,6 +650,7 @@ const trainingAttemptSchema = z.object({questionCount: z.number().int().min(0),correctCount: z.number().int().min(0),latencyMs: z.number().min(0),+ drillData: z.any().optional(),// Deterministic drills retain answer/latency detail for ladder/adaptive// evidence; wordplay keeps its established compact training-question shape.questions: z.array(z.union([questionResultSchema, trainingQuestionSchema])).max(500).optional(),@@ -632,6 +661,29 @@ const trainingAttemptSchema = z.object({confidence: z.number().min(0).max(1).nullable().optional(),inputMode: z.string().min(1).max(50).optional().default('unknown'),scorerProvenance: z.string().min(1).max(100).optional().default('post-client'),+ accuracy: z.number().min(0).max(1).nullable().optional(),+ avgResponseMs: z.number().min(0).nullable().optional(),+ answeredCount: z.number().int().min(0).optional(),+ totalCount: z.number().int().min(0).optional(),+ attemptCount: z.number().int().min(0).optional(),+ errorCount: z.number().int().min(0).optional(),+ medianMs: z.number().min(0).nullable().optional(),+ bestMs: z.number().min(0).nullable().optional(),+ span: z.number().int().min(0).optional(),+ hits: z.number().int().min(0).optional(),+ misses: z.number().int().min(0).optional(),+ omissions: z.number().int().min(0).optional(),+ commissionErrors: z.number().int().min(0).optional(),+ falseAlarms: z.number().int().min(0).optional(),+ correctRejections: z.number().int().min(0).optional(),+ switchCostMs: z.number().nullable().optional(),+ switchAccuracy: z.number().min(0).max(1).nullable().optional(),+ repeatAccuracy: z.number().min(0).max(1).nullable().optional(),+ congruencyCostMs: z.number().nullable().optional(),+ congruentAccuracy: z.number().min(0).max(1).nullable().optional(),+ incongruentAccuracy: z.number().min(0).max(1).nullable().optional(),+ falseAlarmRate: z.number().min(0).max(1).nullable().optional(),+ latencyDistributionMs: z.array(z.number().min(0)).max(500).optional(),}).superRefine((attempt, ctx) => {if (attempt.correctCount > attempt.questionCount) {ctx.addIssue({ code: 'custom', path: ['correctCount'], message: 'correctCount cannot exceed questionCount' });diff --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.jsindex b8b3d84eec..caf26b6ad6 100644--- a/server/lib/postValidation.test.js+++ b/server/lib/postValidation.test.js@@ -5,6 +5,7 @@ import {postSessionSubmitSchema,postDrillRequestSchema,trainingEntrySchema,+ trainingRunSubmitSchema,memoryItemCreateSchema,memoryScheduleSchema,memoryPracticeSchema,@@ -557,6 +558,25 @@ describe('drillTypeConfigSchema numeric bounds', () => {});});+ it('accepts seeded executive-control difficulty knobs', () => {+ const parsed = postDrillRequestSchema.parse({+ type: 'task-switching',+ config: {+ seed: 'example-seed', ruleCount: 3, switchRatePct: 65,+ cueStimulusIntervalMs: 350, incongruentPct: 80, responseDeadlineMs: 1600,+ noGoPct: 40, lureSimilarity: 'high', congruentPct: 40,+ flankerDistance: 1, flankerStrength: 3,+ },+ });+ expect(parsed.config).toMatchObject({ seed: 'example-seed', ruleCount: 3, switchRatePct: 65, lureSimilarity: 'high', flankerStrength: 3 });+ });++ it('rejects out-of-range executive-control knobs', () => {+ expect(() => postDrillRequestSchema.parse({ type: 'task-switching', config: { ruleCount: 4 } })).toThrow();+ expect(() => postDrillRequestSchema.parse({ type: 'go-no-go', config: { noGoPct: 0 } })).toThrow();+ expect(() => postDrillRequestSchema.parse({ type: 'flanker', config: { flankerStrength: 4 } })).toThrow();+ });+it('rejects out-of-range interference and rotation complexity knobs', () => {expect(() => postDrillRequestSchema.parse({ type: 'stroop', config: { incongruentPct: 101 } })).toThrow();expect(() => postDrillRequestSchema.parse({ type: 'mental-rotation', config: { rotationComplexity: 4 } })).toThrow();@@ -688,6 +708,27 @@ describe('postSessionSubmitSchema client-generated id (issue #2098)', () => {});});+describe('trainingRunSubmitSchema executive-control evidence (#4445)', () => {+ it('preserves drill data and task-specific metrics for server rescoring', () => {+ const parsed = trainingRunSubmitSchema.parse({+ id: '33333333-3333-4333-8333-333333333333',+ attempts: [{+ id: 'attempt-1', module: 'cognitive', drillType: 'flanker',+ difficulty: { seed: 'flanker' },+ drillData: { type: 'flanker', config: { seed: 'flanker' }, trials: [] },+ questionCount: 1, correctCount: 1, latencyMs: 400,+ questions: [{ prompt: 'left-right', index: 0, answered: 'right', correct: true, responseMs: 400, congruent: false }],+ accuracy: 1, completion: 1, congruencyCostMs: null,+ incongruentAccuracy: 1, omissions: 0, commissionErrors: 0,+ latencyDistributionMs: [400],+ }],+ });+ expect(parsed.attempts[0]).toMatchObject({ drillType: 'flanker', accuracy: 1, incongruentAccuracy: 1, omissions: 0 });+ expect(parsed.attempts[0].drillData.config.seed).toBe('flanker');+ expect(parsed.attempts[0].questions[0].congruent).toBe(false);+ });+});+// Practice Plan config blocks (issue #3252). All three are additive: a config// saved by the pre-#3252 UI must still validate byte-for-byte unchanged, which// is what makes this shippable with no migration.diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex acae9e1363..54e8558c00 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -119,7 +119,12 @@ const DEFAULT_CONFIG = {'stroop': { enabled: true, progressive: true, count: 15, incongruentPct: 75 },'schulte-table': { enabled: true, progressive: true, size: 5 },'mental-rotation': { enabled: true, progressive: true, count: 8, rotationComplexity: 3, optionCount: 4 },- 'reaction-time': { enabled: true, mode: 'simple', count: 15, minDelayMs: 1000, maxDelayMs: 3000, choices: 3 }+ 'reaction-time': { enabled: true, mode: 'simple', count: 15, minDelayMs: 1000, maxDelayMs: 3000, choices: 3 },+ // Executive-control pack is opt-in for existing installs: additive config+ // must not silently lengthen a user's established composed session.+ 'task-switching': { enabled: false, progressive: true, count: 18, ruleCount: 2, switchRatePct: 50, cueStimulusIntervalMs: 700, incongruentPct: 50, responseDeadlineMs: 2200 },+ 'go-no-go': { enabled: false, progressive: true, count: 20, noGoPct: 25, stimulusMs: 600, lureSimilarity: 'low', responseDeadlineMs: 1400 },+ 'flanker': { enabled: false, progressive: true, count: 20, congruentPct: 60, flankerDistance: 2, flankerStrength: 2, responseDeadlineMs: 1600 }}},// Memory practice (issue #3252). Present so the block's shape is discoverable@@ -314,6 +319,11 @@ export async function submitPostSession(sessionData) {answeredCount: _ac, totalCount: _tc, attemptCount: _attempts, errorCount: _errors,medianMs: _med, bestMs: _best, span: _span,hits: _h, misses: _m, falseAlarms: _fa, correctRejections: _cr,+ omissions: _omissions, commissionErrors: _commissionErrors,+ switchCostMs: _switchCost, switchAccuracy: _switchAccuracy, repeatAccuracy: _repeatAccuracy,+ congruencyCostMs: _congruencyCost, congruentAccuracy: _congruentAccuracy,+ incongruentAccuracy: _incongruentAccuracy, falseAlarmRate: _falseAlarmRate,+ latencyDistributionMs: _latencyDistribution,...rest} = t || {};@@ -356,7 +366,7 @@ export async function submitPostSession(sessionData) {// persisted alongside the blended score (issue #2094).if (COGNITIVE_DRILL_TYPES.includes(rest.type)) {const scored = scoreCognitiveDrill(rest.type, rest.drillData, rest.questions || []);- return { ...rest, ...scored };+ return { ...rest, ...scored, scorerProvenance: 'server-deterministic' };}// Math drills: strip correct from individual questions and rescore@@ -1671,6 +1681,9 @@ export function generateDrill(type, config = {}) {case 'schulte-table':case 'mental-rotation':case 'reaction-time':+ case 'task-switching':+ case 'go-no-go':+ case 'flanker':return generateCognitiveDrill(type, config);default:return null;diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.jsindex 53a0bc6281..0d113e2e95 100644--- a/server/services/meatspacePost.test.js+++ b/server/services/meatspacePost.test.js@@ -2186,7 +2186,7 @@ describe('progressive cognitive drills', () => {expect(progress['n-back'].levels[1].mastered).toBe(true);expect(progress['n-back'].levels[2].mastered).toBe(false);// Every laddered type reports; reaction-time is absent.- expect(Object.keys(progress).sort()).toEqual(['digit-span', 'mental-rotation', 'n-back', 'schulte-table', 'stroop']);+ expect(Object.keys(progress).sort()).toEqual(['digit-span', 'flanker', 'go-no-go', 'mental-rotation', 'n-back', 'schulte-table', 'stroop', 'task-switching']);});it('difficulty stamp survives submitPostSession (stored task carries config.level)', async () => {@@ -2351,15 +2351,57 @@ describe('getSessionSkillContext', () => {{ type: 'multiplication', config: { level: 2 }, questions: [{ answered: 1, correct: true }] },{ type: 'powers', config: { level: 1 }, questions: [{ answered: 81, correct: true }] },{ type: 'n-back', config: { level: 1 }, accuracy: 0.9, questions: [] },+ { type: 'task-switching', config: { level: 2 }, accuracy: 0.9, questions: [] },+ { type: 'go-no-go', config: { level: 1 }, accuracy: 0.9, questions: [] },+ { type: 'flanker', config: { level: 3 }, accuracy: 0.9, questions: [] },{ type: 'memory-sequence', memoryItemId: 'song-1', questions: [{ chunkId: 'verse-1', correct: true }, { chunkId: 'verse-2', correct: true }] },] };const { practicedSkillIds, reviewResults } = getSessionSkillContext(session);expect(reviewResults).toEqual([]);expect(practicedSkillIds.sort()).toEqual([- 'cognitive:n-back:L1', 'memory:song-1:verse-1', 'memory:song-1:verse-2', 'multiplication:L2', 'powers:L1',+ 'cognitive:flanker:L3', 'cognitive:go-no-go:L1', 'cognitive:n-back:L1', 'cognitive:task-switching:L2',+ 'memory:song-1:verse-1', 'memory:song-1:verse-2', 'multiplication:L2', 'powers:L1',]);});+ it('regenerates a due executive-control review at its mastered ladder rung', async () => {+ readJSONFile.mockImplementation((path, defaultValue) => {+ const p = String(path);+ if (p.includes('post-review-schedule')) return Promise.resolve({+ skills: {+ 'cognitive:flanker:L2': {+ skillId: 'cognitive:flanker:L2',+ kind: 'cognitive',+ label: 'Flanker Balanced field',+ drillType: 'flanker',+ level: 2,+ config: { level: 2, congruentPct: 50, flankerDistance: 'near', flankerStrength: 'strong' },+ nextReviewAt: '2020-01-01T00:00:00.000Z',+ status: 'fresh',+ },+ },+ });+ if (p.includes('post-config')) return Promise.resolve({+ cognitive: { drillTypes: { flanker: { enabled: true, progressive: true } } },+ });+ return Promise.resolve(defaultValue);+ });++ const [rep] = await getPostReviewReps(new Date('2026-07-31T00:00:00.000Z'));+ expect(rep).toMatchObject({+ type: 'flanker',+ config: {+ level: 2,+ congruentPct: 50,+ flankerDistance: 'near',+ flankerStrength: 'strong',+ review: true,+ reviewSkillId: 'cognitive:flanker:L2',+ },+ });+ expect(generateDrill(rep.type, rep.config).trials.length).toBeGreaterThan(0);+ });+it('regenerates a due Powers review from only its mastered technique rung', async () => {readJSONFile.mockImplementation((path, defaultValue) => {if (String(path).includes('post-review-schedule')) return Promise.resolve({diff --git a/server/services/meatspacePostCognitive.js b/server/services/meatspacePostCognitive.jsindex 289ac22713..0996a5873f 100644--- a/server/services/meatspacePostCognitive.js+++ b/server/services/meatspacePostCognitive.js@@ -8,6 +8,9 @@* - schulte-table (visual attention) — scan a shuffled grid for sequential numbers* - mental-rotation (spatial reasoning) — pick the rotated (not mirrored) match* - reaction-time (processing speed) — simple/choice reaction-time baseline+ * - task-switching (rule switching) — apply a cued classification rule+ * - go-no-go (response inhibition) — respond to go stimuli, withhold to lures+ * - flanker (interference control) — report a target direction around distractors** These are deterministic: the drill's answer key lives in the generated data* and every score is recomputed here on session submit, so a client-supplied@@ -20,7 +23,17 @@ import { shuffle } from '../lib/arrayUtils.js';// Coarse module tag stored on scored cognitive tasks, so stats read as// `byDrill['cognitive:<type>']` (parallel to `mental-math:<type>`).export const COGNITIVE_MODULE = 'cognitive';-export const COGNITIVE_DRILL_TYPES = ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time'];+export const COGNITIVE_DRILL_TYPES = [+ 'n-back',+ 'digit-span',+ 'stroop',+ 'schulte-table',+ 'mental-rotation',+ 'reaction-time',+ 'task-switching',+ 'go-no-go',+ 'flanker',+];const NBACK_LETTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];@@ -51,6 +64,43 @@ function pick(arr) {return arr[Math.floor(Math.random() * arr.length)];}+function seedString(value) {+ if (value != null && String(value).trim()) return String(value).trim().slice(0, 100);+ return `${Date.now().toString(36)}-${Math.floor(Math.random() * 0xffffffff).toString(36)}`;+}++// Mulberry32 seeded from an FNV-1a-style string hash. The generated drill+// stores the normalized seed in config, so the same seed + knobs reconstructs+// the same answer key during server rescoring and in focused regression tests.+function seededRandom(seed) {+ let state = 2166136261;+ for (const char of seed) {+ state ^= char.charCodeAt(0);+ state = Math.imul(state, 16777619);+ }+ return () => {+ state |= 0;+ state = (state + 0x6D2B79F5) | 0;+ let t = state;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++function pickWith(arr, random) {+ return arr[Math.floor(random() * arr.length)];+}++function shuffleWith(items, random) {+ const out = [...items];+ for (let i = out.length - 1; i > 0; i -= 1) {+ const j = Math.floor(random() * (i + 1));+ [out[i], out[j]] = [out[j], out[i]];+ }+ return out;+}+function clampMs(ms, refMs) {return Math.min(Math.max(Number(ms) || 0, 0), refMs);}@@ -360,6 +410,117 @@ export function generateReactionTime(config = {}) {return { type: 'reaction-time', config: trialConfig, trials };}+const TASK_SWITCH_RULES = [+ { id: 'color', values: ['blue', 'orange'] },+ { id: 'shape', values: ['circle', 'triangle'] },+ { id: 'fill', values: ['solid', 'outline'] },+];++function taskSwitchAnswer(trial) {+ const rule = TASK_SWITCH_RULES.find(candidate => candidate.id === trial?.rule);+ const value = trial?.stimulus?.[trial?.rule];+ const index = rule?.values.indexOf(value) ?? -1;+ return index === 0 ? 'left' : index === 1 ? 'right' : null;+}++/** Seeded cued task switching with an exact switch/conflict mix. */+export function generateTaskSwitching(config = {}) {+ const seed = seedString(config.seed);+ const random = seededRandom(seed);+ const count = clampInt(config.count, 6, 50, 18);+ const ruleCount = clampInt(config.ruleCount, 2, 3, 2);+ const switchRatePct = clampInt(config.switchRatePct, 0, 100, 50);+ const cueStimulusIntervalMs = clampInt(config.cueStimulusIntervalMs, 100, 2000, 700);+ const incongruentPct = clampInt(config.incongruentPct, 0, 100, 50);+ const responseDeadlineMs = clampInt(config.responseDeadlineMs, 500, 5000, 2200);+ const rules = TASK_SWITCH_RULES.slice(0, ruleCount);+ const switchCount = Math.round(Math.max(0, count - 1) * switchRatePct / 100);+ const switchFlags = [false, ...shuffleWith([+ ...Array.from({ length: switchCount }, () => true),+ ...Array.from({ length: Math.max(0, count - 1 - switchCount) }, () => false),+ ], random)];+ const incongruentCount = Math.round(count * incongruentPct / 100);+ const conflictFlags = shuffleWith([+ ...Array.from({ length: incongruentCount }, () => true),+ ...Array.from({ length: count - incongruentCount }, () => false),+ ], random);+ let currentRule = pickWith(rules, random);+ const trials = switchFlags.map((switched, index) => {+ if (switched) currentRule = pickWith(rules.filter(rule => rule.id !== currentRule.id), random);+ const activeIndex = random() < 0.5 ? 0 : 1;+ const stimulus = {};+ for (const rule of rules) stimulus[rule.id] = rule.values[activeIndex];+ if (conflictFlags[index]) {+ const competing = pickWith(rules.filter(rule => rule.id !== currentRule.id), random);+ stimulus[competing.id] = competing.values[1 - activeIndex];+ }+ return {+ rule: currentRule.id,+ stimulus,+ switched,+ incongruent: conflictFlags[index],+ };+ });+ return {+ type: 'task-switching',+ config: { seed, count, ruleCount, switchRatePct, cueStimulusIntervalMs, incongruentPct, responseDeadlineMs },+ rules,+ trials,+ };+}++/** Seeded Go/No-Go sequence with an exact no-go frequency. */+export function generateGoNoGo(config = {}) {+ const seed = seedString(config.seed);+ const random = seededRandom(seed);+ const count = clampInt(config.count, 6, 60, 20);+ const noGoPct = clampInt(config.noGoPct, 5, 80, 25);+ const stimulusMs = clampInt(config.stimulusMs, 100, 2000, 600);+ const responseDeadlineMs = clampInt(config.responseDeadlineMs, stimulusMs, 5000, 1400);+ const lureSimilarity = config.lureSimilarity === 'high' ? 'high' : 'low';+ const noGoCount = Math.round(count * noGoPct / 100);+ const flags = shuffleWith([+ ...Array.from({ length: noGoCount }, () => true),+ ...Array.from({ length: count - noGoCount }, () => false),+ ], random);+ const trials = flags.map((noGo, index) => ({+ kind: noGo ? 'no-go' : 'go',+ symbol: lureSimilarity === 'high' ? (noGo ? '◉' : '●') : (noGo ? '■' : '●'),+ tone: lureSimilarity === 'high' ? (noGo ? 'amber' : 'green') : (noGo ? 'red' : 'green'),+ variant: index % 2,+ }));+ return {+ type: 'go-no-go',+ config: { seed, count, noGoPct, stimulusMs, lureSimilarity, responseDeadlineMs },+ trials,+ };+}++/** Seeded Eriksen-style flanker trials with an exact congruency mix. */+export function generateFlanker(config = {}) {+ const seed = seedString(config.seed);+ const random = seededRandom(seed);+ const count = clampInt(config.count, 6, 60, 20);+ const congruentPct = clampInt(config.congruentPct, 0, 100, 60);+ const flankerDistance = clampInt(config.flankerDistance, 1, 4, 2);+ const flankerStrength = clampInt(config.flankerStrength, 1, 3, 2);+ const responseDeadlineMs = clampInt(config.responseDeadlineMs, 500, 5000, 1600);+ const congruentCount = Math.round(count * congruentPct / 100);+ const flags = shuffleWith([+ ...Array.from({ length: congruentCount }, () => true),+ ...Array.from({ length: count - congruentCount }, () => false),+ ], random);+ const trials = flags.map(congruent => {+ const target = random() < 0.5 ? 'left' : 'right';+ return { target, flanker: congruent ? target : target === 'left' ? 'right' : 'left', congruent };+ });+ return {+ type: 'flanker',+ config: { seed, count, congruentPct, flankerDistance, flankerStrength, responseDeadlineMs },+ trials,+ };+}+export function generateCognitiveDrill(type, config = {}) {let drill;switch (type) {@@ -381,6 +542,15 @@ export function generateCognitiveDrill(type, config = {}) {case 'reaction-time':drill = generateReactionTime(config);break;+ case 'task-switching':+ drill = generateTaskSwitching(config);+ break;+ case 'go-no-go':+ drill = generateGoNoGo(config);+ break;+ case 'flanker':+ drill = generateFlanker(config);+ break;default:return null;}@@ -686,6 +856,157 @@ function scoreReactionTime(drillData, questions) {};}+function averageLatency(questions) {+ const timed = questions.filter(question => question.correct && question.responseMs > 0);+ return timed.length ? Math.round(timed.reduce((sum, question) => sum + question.responseMs, 0) / timed.length) : null;+}++function groupAccuracy(questions, predicate) {+ const group = questions.filter(predicate);+ return group.length ? group.filter(question => question.correct).length / group.length : null;+}++function costBetween(questions, costlyPredicate, baselinePredicate) {+ const costly = averageLatency(questions.filter(costlyPredicate));+ const baseline = averageLatency(questions.filter(baselinePredicate));+ return costly == null || baseline == null ? null : costly - baseline;+}++function executiveMetrics(recomputed, refMs) {+ const totalCount = recomputed.length;+ const attempted = recomputed.filter(question => question.attempted);+ const answered = recomputed.filter(question => question.answered != null);+ const accuracy = attempted.length ? attempted.filter(question => question.correct).length / attempted.length : null;+ const completion = totalCount ? attempted.length / totalCount : null;+ const avgResponseMs = averageLatency(attempted);+ const speedBonus = avgResponseMs == null ? 0 : Math.max(0, 1 - avgResponseMs / refMs);+ return {+ score: Math.round(((accuracy || 0) * 0.8 + speedBonus * 0.2) * (completion || 0) * 100),+ questions: recomputed,+ accuracy,+ completion,+ avgResponseMs,+ answeredCount: answered.length,+ totalCount,+ commissionErrors: answered.filter(question => !question.correct).length,+ omissions: attempted.filter(question => question.answered == null && !question.correct).length,+ latencyDistributionMs: answered.map(question => question.responseMs).filter(ms => ms > 0),+ };+}++function scoreTaskSwitching(drillData, questions) {+ const regenerated = generateTaskSwitching(drillData?.config || {});+ const trials = regenerated.trials;+ const refMs = regenerated.config.responseDeadlineMs;+ const responses = new Map(questions.map(question => [question.index, question]));+ const recomputed = trials.map((trial, index) => {+ const question = responses.get(index);+ const expected = taskSwitchAnswer(trial);+ const answered = question?.answered === 'left' || question?.answered === 'right' ? question.answered : null;+ return {+ prompt: trial.rule || '',+ index,+ expected,+ answered,+ correct: question != null && expected != null && answered === expected,+ attempted: question != null,+ responseMs: clampMs(question?.responseMs, refMs),+ rule: trial.rule,+ switched: trial.switched === true,+ incongruent: trial.incongruent === true,+ };+ });+ return {+ ...executiveMetrics(recomputed, refMs),+ switchCostMs: costBetween(recomputed, question => question.switched, question => !question.switched),+ switchAccuracy: groupAccuracy(recomputed, question => question.attempted && question.switched),+ repeatAccuracy: groupAccuracy(recomputed, question => question.attempted && !question.switched),+ };+}++function scoreGoNoGo(drillData, questions) {+ const regenerated = generateGoNoGo(drillData?.config || {});+ const trials = regenerated.trials;+ const refMs = regenerated.config.responseDeadlineMs;+ const responses = new Map(questions.map(question => [question.index, question]));+ const recomputed = trials.map((trial, index) => {+ const question = responses.get(index);+ const shouldRespond = trial.kind === 'go';+ const answered = question?.answered === 'go' ? 'go' : null;+ return {+ prompt: trial.symbol || '',+ index,+ expected: shouldRespond ? 'go' : 'withhold',+ answered,+ correct: question != null && (shouldRespond ? answered === 'go' : answered == null),+ attempted: question != null,+ responseMs: clampMs(question?.responseMs, refMs),+ noGo: !shouldRespond,+ };+ });+ const attempted = recomputed.filter(question => question.attempted);+ const hits = attempted.filter(question => !question.noGo && question.answered === 'go').length;+ const omissions = attempted.filter(question => !question.noGo && question.answered == null).length;+ const falseAlarms = attempted.filter(question => question.noGo && question.answered === 'go').length;+ const correctRejections = attempted.filter(question => question.noGo && question.answered == null).length;+ const goCount = hits + omissions;+ const noGoCount = falseAlarms + correctRejections;+ const hitRate = goCount ? hits / goCount : null;+ const correctRejectionRate = noGoCount ? correctRejections / noGoCount : null;+ const accuracy = hitRate == null && correctRejectionRate == null+ ? null+ : ((hitRate ?? 0.5) + (correctRejectionRate ?? 0.5)) / 2;+ const pressed = attempted.filter(question => question.answered === 'go');+ const latencies = pressed.map(question => question.responseMs).filter(ms => ms > 0);+ const completion = recomputed.length ? attempted.length / recomputed.length : null;+ return {+ score: accuracy == null ? 0 : Math.round(accuracy * (completion || 0) * 100),+ questions: recomputed,+ accuracy,+ completion,+ avgResponseMs: averageLatency(attempted),+ medianMs: median(latencies),+ bestMs: latencies.length ? Math.min(...latencies) : null,+ answeredCount: pressed.length,+ totalCount: recomputed.length,+ hits,+ omissions,+ falseAlarms,+ commissionErrors: falseAlarms,+ correctRejections,+ falseAlarmRate: noGoCount ? falseAlarms / noGoCount : null,+ latencyDistributionMs: latencies,+ };+}++function scoreFlanker(drillData, questions) {+ const regenerated = generateFlanker(drillData?.config || {});+ const trials = regenerated.trials;+ const refMs = regenerated.config.responseDeadlineMs;+ const responses = new Map(questions.map(question => [question.index, question]));+ const recomputed = trials.map((trial, index) => {+ const question = responses.get(index);+ const expected = trial.target === 'left' || trial.target === 'right' ? trial.target : null;+ const answered = question?.answered === 'left' || question?.answered === 'right' ? question.answered : null;+ return {+ prompt: `${trial.flanker || ''}-${trial.target || ''}`,+ index,+ expected,+ answered,+ correct: question != null && expected != null && answered === expected,+ attempted: question != null,+ responseMs: clampMs(question?.responseMs, refMs),+ congruent: trial.congruent === true,+ };+ });+ return {+ ...executiveMetrics(recomputed, refMs),+ congruencyCostMs: costBetween(recomputed, question => !question.congruent, question => question.congruent),+ congruentAccuracy: groupAccuracy(recomputed, question => question.attempted && question.congruent),+ incongruentAccuracy: groupAccuracy(recomputed, question => question.attempted && !question.congruent),+ };+}+/*** Rescore a completed cognitive drill from its generated `drillData` + the* player's per-trial `questions`. Returns `{ score, questions, span? }`.@@ -705,6 +1026,12 @@ export function scoreCognitiveDrill(type, drillData, questions = []) {return scoreMentalRotation(drillData, list);case 'reaction-time':return scoreReactionTime(drillData, list);+ case 'task-switching':+ return scoreTaskSwitching(drillData, list);+ case 'go-no-go':+ return scoreGoNoGo(drillData, list);+ case 'flanker':+ return scoreFlanker(drillData, list);default:return { score: 0, questions: list };}diff --git a/server/services/meatspacePostCognitive.test.js b/server/services/meatspacePostCognitive.test.jsindex 73e349c5c7..77959e71a3 100644--- a/server/services/meatspacePostCognitive.test.js+++ b/server/services/meatspacePostCognitive.test.js@@ -9,6 +9,9 @@ import {generateSchulteTable,generateMentalRotation,generateReactionTime,+ generateTaskSwitching,+ generateGoNoGo,+ generateFlanker,generateCognitiveDrill,scoreCognitiveDrill,rotateCells,@@ -79,11 +82,14 @@ describe('cognitive drill generators', () => {expect(generateCognitiveDrill('schulte-table').type).toBe('schulte-table');expect(generateCognitiveDrill('mental-rotation').type).toBe('mental-rotation');expect(generateCognitiveDrill('reaction-time').type).toBe('reaction-time');+ expect(generateCognitiveDrill('task-switching').type).toBe('task-switching');+ expect(generateCognitiveDrill('go-no-go').type).toBe('go-no-go');+ expect(generateCognitiveDrill('flanker').type).toBe('flanker');expect(generateCognitiveDrill('nope')).toBeNull();});- it('exposes exactly the six shipped cognitive types', () => {- expect(COGNITIVE_DRILL_TYPES).toEqual(['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time']);+ it('exposes exactly the nine shipped cognitive types', () => {+ expect(COGNITIVE_DRILL_TYPES).toEqual(['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time', 'task-switching', 'go-no-go', 'flanker']);});it('schulte-table shuffles 1..size*size into every cell exactly once', () => {@@ -166,6 +172,37 @@ describe('cognitive drill generators', () => {expect(trial.target).toBeLessThan(4);}});++ it('executive-control generators reproduce the same trials from the same seed', () => {+ for (const generate of [generateTaskSwitching, generateGoNoGo, generateFlanker]) {+ const first = generate({ seed: 'example-seed', count: 12 });+ const second = generate({ seed: 'example-seed', count: 12 });+ expect(second).toEqual(first);+ expect(generate({ seed: 'different-seed', count: 12 }).trials).not.toEqual(first.trials);+ }+ });++ it('task switching applies rule-count, switch-rate, cue, conflict, and deadline levers', () => {+ const drill = generateTaskSwitching({ seed: 'switch', count: 10, ruleCount: 3, switchRatePct: 50, cueStimulusIntervalMs: 400, incongruentPct: 60, responseDeadlineMs: 1200 });+ expect(drill.config).toMatchObject({ ruleCount: 3, switchRatePct: 50, cueStimulusIntervalMs: 400, incongruentPct: 60, responseDeadlineMs: 1200 });+ expect(drill.rules).toHaveLength(3);+ expect(drill.trials.filter(trial => trial.switched)).toHaveLength(5);+ expect(drill.trials.filter(trial => trial.incongruent)).toHaveLength(6);+ });++ it('go/no-go applies no-go frequency, stimulus duration, lure similarity, and deadline levers', () => {+ const drill = generateGoNoGo({ seed: 'inhibit', count: 20, noGoPct: 35, stimulusMs: 350, lureSimilarity: 'high', responseDeadlineMs: 900 });+ expect(drill.config).toMatchObject({ noGoPct: 35, stimulusMs: 350, lureSimilarity: 'high', responseDeadlineMs: 900 });+ expect(drill.trials.filter(trial => trial.kind === 'no-go')).toHaveLength(7);+ expect(new Set(drill.trials.map(trial => trial.symbol))).toEqual(new Set(['●', '◉']));+ });++ it('flanker applies congruency, distance, strength, and deadline levers', () => {+ const drill = generateFlanker({ seed: 'flank', count: 20, congruentPct: 40, flankerDistance: 1, flankerStrength: 3, responseDeadlineMs: 1000 });+ expect(drill.config).toMatchObject({ congruentPct: 40, flankerDistance: 1, flankerStrength: 3, responseDeadlineMs: 1000 });+ expect(drill.trials.filter(trial => trial.congruent)).toHaveLength(8);+ expect(drill.trials.filter(trial => !trial.congruent).every(trial => trial.target !== trial.flanker)).toBe(true);+ });});describe('cognitive drill scorers (recompute the answer key, never trust client)', () => {@@ -463,4 +500,64 @@ describe('cognitive drill scorers (recompute the answer key, never trust client)]);expect(wrong.questions[0].correct).toBe(false);});++ it('task switching regenerates the seeded answer key and records switch cost + omissions', () => {+ const drillData = generateTaskSwitching({ seed: 'score-switch', count: 8, switchRatePct: 50, incongruentPct: 50 });+ const answers = drillData.trials.map((trial, index) => {+ const values = { color: ['blue', 'orange'], shape: ['circle', 'triangle'], fill: ['solid', 'outline'] }[trial.rule];+ const expected = values.indexOf(trial.stimulus[trial.rule]) === 0 ? 'left' : 'right';+ return { index, answered: expected, correct: false, responseMs: trial.switched ? 800 : 400 };+ });+ // Stored trial data is advisory; scoring reconstructs it from config.seed.+ drillData.trials = drillData.trials.map(() => ({ rule: 'color', stimulus: { color: 'orange' } }));+ const result = scoreCognitiveDrill('task-switching', drillData, answers);+ expect(result.score).toBeGreaterThan(80);+ expect(result.accuracy).toBe(1);+ expect(result.switchCostMs).toBe(400);+ expect(result.switchAccuracy).toBe(1);+ expect(result.repeatAccuracy).toBe(1);+ expect(result.omissions).toBe(0);+ expect(result.latencyDistributionMs).toHaveLength(8);+ });++ it('go/no-go records false alarms, omissions, balanced accuracy, and latency distribution', () => {+ const drillData = generateGoNoGo({ seed: 'score-inhibit', count: 10, noGoPct: 30 });+ const perfect = drillData.trials.map((trial, index) => ({ index, answered: trial.kind === 'go' ? 'go' : null, responseMs: trial.kind === 'go' ? 350 : 0 }));+ const result = scoreCognitiveDrill('go-no-go', drillData, perfect);+ expect(result).toMatchObject({ score: 100, accuracy: 1, falseAlarms: 0, omissions: 0, commissionErrors: 0 });+ expect(result.correctRejections).toBe(3);+ expect(result.latencyDistributionMs).toHaveLength(7);++ const alwaysPress = scoreCognitiveDrill('go-no-go', drillData, drillData.trials.map((_, index) => ({ index, answered: 'go', correct: true, responseMs: 250 })));+ expect(alwaysPress.falseAlarms).toBe(3);+ expect(alwaysPress.commissionErrors).toBe(3);+ expect(alwaysPress.falseAlarmRate).toBe(1);+ expect(alwaysPress.score).toBe(50);+ });++ it('flanker regenerates targets and records congruency cost + interference accuracy', () => {+ const drillData = generateFlanker({ seed: 'score-flank', count: 10, congruentPct: 50 });+ const answers = drillData.trials.map((trial, index) => ({ index, answered: trial.target, correct: false, responseMs: trial.congruent ? 300 : 700 }));+ drillData.trials = drillData.trials.map(() => ({ target: 'left', flanker: 'left', congruent: true }));+ const result = scoreCognitiveDrill('flanker', drillData, answers);+ expect(result.accuracy).toBe(1);+ expect(result.congruencyCostMs).toBe(400);+ expect(result.congruentAccuracy).toBe(1);+ expect(result.incongruentAccuracy).toBe(1);+ expect(result.omissions).toBe(0);+ });++ it('keeps an early exit distinct from timed omissions', () => {+ const drillData = generateFlanker({ seed: 'partial-flank', count: 8, congruentPct: 50 });+ const answers = drillData.trials.slice(0, 3).map((trial, index) => ({+ index,+ answered: index === 2 ? null : trial.target,+ responseMs: index === 2 ? drillData.config.responseDeadlineMs : 300,+ }));+ const result = scoreCognitiveDrill('flanker', drillData, answers);+ expect(result.totalCount).toBe(8);+ expect(result.completion).toBe(3 / 8);+ expect(result.omissions).toBe(1);+ expect(result.questions.slice(3).every(question => !question.attempted)).toBe(true);+ });});diff --git a/server/services/meatspacePostRecommendations.test.js b/server/services/meatspacePostRecommendations.test.jsindex 9ff8f769ae..d2115aba05 100644--- a/server/services/meatspacePostRecommendations.test.js+++ b/server/services/meatspacePostRecommendations.test.js@@ -127,16 +127,27 @@ describe('stalledProgressions', () => {});it('includes cognitive ladders and a Morse Koch step once level is set', () => {- const cog = { 'n-back': { level: 0, atHardest: false, currentMastered: false, thresholds: { minSamples: 3 }, levels: [- { level: 0, label: '1-back @ 2500ms', samples: 1, mastered: false },- { level: 1, label: '2-back @ 2500ms', samples: 0, mastered: false },- ] } };+ const cognitiveLadder = (label) => ({ level: 0, atHardest: false, currentMastered: false, thresholds: { minSamples: 3 }, levels: [+ { level: 0, label, samples: 1, mastered: false },+ { level: 1, label: `Harder ${label}`, samples: 0, mastered: false },+ ] });+ const cog = {+ 'n-back': cognitiveLadder('1-back @ 2500ms'),+ 'task-switching': cognitiveLadder('Two rules'),+ 'go-no-go': cognitiveLadder('Distinct lures'),+ flanker: cognitiveLadder('Mostly congruent'),+ };const out = stalledProgressions(null, null, cog, { kochLevel: 5, kochLevelSet: true, maxKochLevel: 41 });const nback = out.find(o => o.drillType === 'n-back');expect(nback.remaining).toBe(2); // 3 - 1const morse = out.find(o => o.drillType === 'morse-copy');expect(morse.deepLink).toBe('/post/morse/copy');expect(morse.nextLabel).toBe('Koch level 6');+ expect(out).toEqual(expect.arrayContaining([+ expect.objectContaining({ drillType: 'task-switching', label: 'Task Switching' }),+ expect.objectContaining({ drillType: 'go-no-go', label: 'Go No Go' }),+ expect.objectContaining({ drillType: 'flanker', label: 'Flanker' }),+ ]));});it('does not surface Morse for a fresh install (level not set)', () => {diff --git a/server/services/meatspacePostTraining.js b/server/services/meatspacePostTraining.jsindex 79fa89791d..83f89aa293 100644--- a/server/services/meatspacePostTraining.js+++ b/server/services/meatspacePostTraining.js@@ -11,39 +11,58 @@ import { recordDayKey, ymdShift } from '../lib/postStreak.js';import { getUnifiedActivityStreak } from './postActivityStreak.js';import { getAllTrainingEntries } from './postTrainingLogStore.js';import { saveStoredTrainingRun } from './postRunStore.js';+import { COGNITIVE_DRILL_TYPES, scoreCognitiveDrill } from './meatspacePostCognitive.js';export { getAllTrainingEntries };function trainingAttempt(runId, attempt, position, localDay, startedAt) {- const questionCount = attempt.questionCount ?? attempt.questions?.length ?? 0;- const correctCount = attempt.correctCount- ?? attempt.questions?.filter((question) => question?.correct === true).length+ // Training uses the same server-authoritative deterministic scorer as scored+ // sessions. The client sends drillData + raw answers for immediate feedback,+ // but its correctness, score, error counts, and cost metrics are advisory.+ const scored = COGNITIVE_DRILL_TYPES.includes(attempt.drillType)+ ? scoreCognitiveDrill(attempt.drillType, attempt.drillData, attempt.questions || [])+ : null;+ const normalized = scored ? { ...attempt, ...scored, scorerProvenance: 'server-deterministic' } : attempt;+ const questionCount = scored ? scored.questions.length : normalized.questionCount ?? normalized.questions?.length ?? 0;+ const correctCount = scored+ ? scored.questions.filter((question) => question?.correct === true).length+ : normalized.correctCount+ ?? normalized.questions?.filter((question) => question?.correct === true).length?? 0;- const score = attempt.score !== undefined- ? attempt.score+ const score = normalized.score !== undefined+ ? normalized.score: (questionCount > 0 ? (correctCount / questionCount) * 100 : null);- const id = attempt.id || `${runId}:attempt:${position}`;+ const id = normalized.id || `${runId}:attempt:${position}`;const record = {id,runId,date: localDay,timestamp: startedAt,- module: attempt.module,- drillType: attempt.drillType,- ...(attempt.memoryItemId ? { memoryItemId: attempt.memoryItemId } : {}),+ module: normalized.module,+ drillType: normalized.drillType,+ ...(normalized.memoryItemId ? { memoryItemId: normalized.memoryItemId } : {}),questionCount,correctCount,- totalMs: attempt.latencyMs ?? attempt.totalMs ?? 0,- ...(Array.isArray(attempt.questions) ? { questions: attempt.questions } : {}),- difficulty: attempt.difficulty !== undefined ? attempt.difficulty : (attempt.config ?? null),- configVersion: attempt.configVersion || null,- correct: attempt.correct !== undefined ? attempt.correct : (questionCount > 0 ? correctCount === questionCount : null),+ totalMs: normalized.latencyMs ?? normalized.totalMs ?? 0,+ ...(Array.isArray(normalized.questions) ? { questions: normalized.questions } : {}),+ difficulty: normalized.difficulty !== undefined ? normalized.difficulty : (normalized.config ?? null),+ configVersion: normalized.configVersion || null,+ correct: scored+ ? (questionCount > 0 ? correctCount === questionCount : null)+ : normalized.correct !== undefined ? normalized.correct : (questionCount > 0 ? correctCount === questionCount : null),score,- completion: attempt.completion !== undefined ? attempt.completion : (questionCount > 0 ? 1 : null),- hintUsed: attempt.hintUsed === true,- confidence: attempt.confidence ?? null,- inputMode: attempt.inputMode || 'unknown',- scorerProvenance: attempt.scorerProvenance || 'post-client',+ completion: normalized.completion !== undefined ? normalized.completion : (questionCount > 0 ? 1 : null),+ hintUsed: normalized.hintUsed === true,+ confidence: normalized.confidence ?? null,+ inputMode: normalized.inputMode || 'unknown',+ scorerProvenance: normalized.scorerProvenance || 'post-client',+ ...Object.fromEntries([+ 'accuracy', 'avgResponseMs', 'answeredCount', 'totalCount', 'attemptCount', 'errorCount',+ 'medianMs', 'bestMs', 'span', 'hits', 'misses', 'omissions', 'commissionErrors',+ 'falseAlarms', 'correctRejections', 'switchCostMs', 'switchAccuracy', 'repeatAccuracy',+ 'congruencyCostMs', 'congruentAccuracy', 'incongruentAccuracy', 'falseAlarmRate',+ 'latencyDistributionMs',+ ].filter(key => normalized[key] !== undefined).map(key => [key, normalized[key]])),};return {id,diff --git a/server/services/meatspacePostTraining.test.js b/server/services/meatspacePostTraining.test.jsindex 989475892d..70458e4e4a 100644--- a/server/services/meatspacePostTraining.test.js+++ b/server/services/meatspacePostTraining.test.js@@ -27,6 +27,7 @@ import {getTrainingStats,getTrainingEntries,} from './meatspacePostTraining.js';+import { generateFlanker } from './meatspacePostCognitive.js';beforeEach(() => {vi.clearAllMocks();@@ -153,6 +154,53 @@ describe('submitTrainingRun (#4441)', () => {expect(stored.entries[2].memoryItemId).toBe('memory-1');expect(stored.entries.map((entry) => entry.timestamp)).toEqual(firstTimestamps);});++ it('server-rescores deterministic executive attempts and stores unified task metrics', async () => {+ let stored = { entries: [] };+ readJSONFile.mockImplementation(async () => stored);+ atomicWrite.mockImplementation(async (path, value) => {+ if (String(path).includes('post-training-log')) stored = value;+ });+ const drillData = generateFlanker({ seed: 'training-flanker', count: 6, congruentPct: 50 });+ const questions = drillData.trials.map((trial, index) => ({+ index,+ answered: trial.target,+ correct: false,+ responseMs: trial.congruent ? 300 : 650,+ }));++ const saved = await submitTrainingRun({+ id: '22222222-2222-4222-8222-222222222222',+ attempts: [{+ id: 'executive-attempt',+ module: 'cognitive',+ drillType: 'flanker',+ difficulty: drillData.config,+ drillData,+ questions,+ questionCount: questions.length,+ correctCount: 0,+ latencyMs: 2400,+ score: 0,+ completion: 0,+ scorerProvenance: 'client-deterministic',+ }],+ });++ expect(saved.attempts[0]).toMatchObject({+ id: 'executive-attempt',+ score: 94,+ correctCount: 6,+ accuracy: 1,+ completion: 1,+ congruencyCostMs: 350,+ congruentAccuracy: 1,+ incongruentAccuracy: 1,+ scorerProvenance: 'server-deterministic',+ });+ expect(stored.entries[0].latencyDistributionMs).toHaveLength(6);+ expect(stored.entries[0].questions.every(question => question.correct)).toBe(true);+ });});describe('getTrainingStats', () => {