Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-2006]): add Schulte table, mental rotation, and reaction-time cognitive drills
Adam Eivy68132cb73df4
diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsxindex 05ab2a9f40..2d839edc5c 100644--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx@@ -29,6 +29,12 @@ export default function PostCognitiveDrillRunner({ drill, drillIndex, drillCountreturn <DigitSpanRunner {...shared} />;case 'stroop':return <StroopRunner {...shared} />;+ case 'schulte-table':+ return <SchulteTableRunner {...shared} />;+ case 'mental-rotation':+ return <MentalRotationRunner {...shared} />;+ case 'reaction-time':+ return <ReactionTimeRunner {...shared} />;default:return <div className="text-port-error text-center py-8">Unsupported cognitive drill: {drill.type}</div>;}@@ -54,6 +60,26 @@ function localAccuracyScore(questions) {return Math.round((correct / questions.length) * 100);}+// 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 }) {+ const filled = new Set((cells || []).map(([x, y]) => `${x},${y}`));+ return (+ <div+ className="grid gap-0.5"+ style={{ gridTemplateColumns: `repeat(${size}, ${cellPx}px)`, gridTemplateRows: `repeat(${size}, ${cellPx}px)` }}+ >+ {Array.from({ length: size * size }, (_, i) => {+ const x = i % size;+ const y = Math.floor(i / size);+ return (+ <div key={i} className={`rounded-sm ${filled.has(`${x},${y}`) ? 'bg-rose-400' : 'bg-port-border/30'}`} />+ );+ })}+ </div>+ );+}+// =============================================================================// N-BACK — a letter stream; signal when the current letter matches N steps back// =============================================================================@@ -496,3 +522,428 @@ function StroopRunner({ drill, drillIndex, drillCount, onComplete, isTraining })</div>);}++// =============================================================================+// SCHULTE TABLE — scan a shuffled grid and tap 1, 2, 3... in sequence+// =============================================================================+function SchulteTableRunner({ drill, drillIndex, drillCount, onComplete, isTraining }) {+ const cells = drill.cells || [];+ const size = drill.config?.size || 5;+ const total = cells.length;++ const [target, setTarget] = useState(1);+ const [flash, setFlash] = useState(null); // value of a just-missed (wrong) click+ const questionsRef = useRef([]);+ const stepStartRef = useRef(Date.now());+ const startedAtRef = useRef(Date.now());+ const flashTimeoutRef = useRef(null);++ useEffect(() => () => clearTimeout(flashTimeoutRef.current), []);++ const finish = useCallback(() => {+ onComplete({+ module: 'cognitive',+ type: 'schulte-table',+ config: drill.config,+ drillData: drill,+ questions: questionsRef.current,+ score: localAccuracyScore(questionsRef.current),+ totalMs: Date.now() - startedAtRef.current,+ });+ }, [drill, onComplete]);++ const finishRef = useRef(finish);+ finishRef.current = finish;++ const handleClick = useCallback((value) => {+ if (value !== target) {+ setFlash(value);+ clearTimeout(flashTimeoutRef.current);+ flashTimeoutRef.current = setTimeout(() => setFlash(null), 200);+ return;+ }+ questionsRef.current.push({+ prompt: `${target}`,+ index: target - 1,+ answered: target,+ correct: true,+ responseMs: Date.now() - stepStartRef.current,+ });+ stepStartRef.current = Date.now();+ if (target >= total) finishRef.current();+ else setTarget(t => t + 1);+ }, [target, total]);++ const found = Math.min(target - 1, total);+ const progressPct = total > 0 ? (found / total) * 100 : 0;++ return (+ <div className="max-w-lg mx-auto space-y-6">+ <DrillHeader type="schulte-table" isTraining={isTraining} drillIndex={drillIndex} drillCount={drillCount} />++ <p className="text-center text-sm text-gray-400">+ Tap the numbers in order — <span className="text-rose-400 font-semibold">1, 2, 3...</span> — as fast as you can.+ </p>++ <div className="flex items-center justify-center gap-2 text-sm text-gray-400">+ <span>Find:</span>+ <span className="text-2xl font-mono font-bold text-white">{Math.min(target, total)}</span>+ </div>++ <div+ className="grid gap-1.5 mx-auto w-full"+ style={{ gridTemplateColumns: `repeat(${size}, minmax(0, 1fr))`, maxWidth: `${size * 3.5}rem` }}+ >+ {cells.map((value, i) => {+ const isDone = value < target;+ const isFlashing = flash === value;+ return (+ <button+ key={i}+ type="button"+ onClick={() => handleClick(value)}+ disabled={isDone}+ className={`aspect-square flex items-center justify-center rounded-md font-mono font-semibold text-sm border transition-colors ${+ isDone+ ? 'bg-port-success/10 border-port-success/30 text-port-success/50'+ : isFlashing+ ? 'bg-port-error/30 border-port-error/60 text-white'+ : 'bg-port-card border-port-border text-white hover:bg-port-bg'+ }`}+ >+ {value}+ </button>+ );+ })}+ </div>++ <div className="space-y-1">+ <div className="flex justify-between text-xs text-gray-500">+ <span>{found} / {total} found</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" style={{ width: `${progressPct}%` }} />+ </div>+ </div>+ </div>+ );+}++// =============================================================================+// MENTAL ROTATION — pick the shape that's the SAME, just rotated (not mirrored)+// =============================================================================+function MentalRotationRunner({ drill, drillIndex, drillCount, onComplete, isTraining }) {+ const trials = drill.trials || [];+ const gridSize = drill.config?.gridSize || 4;++ const [trialIdx, setTrialIdx] = useState(0);+ const [feedback, setFeedback] = useState(null); // { correct, expected, isLast } training reveal+ const answersRef = useRef([]);+ const trialStartRef = useRef(Date.now());+ const startedAtRef = useRef(Date.now());+ const advancingRef = useRef(false);++ const finish = useCallback(() => {+ const questions = answersRef.current.filter(Boolean);+ onComplete({+ module: 'cognitive',+ type: 'mental-rotation',+ config: drill.config,+ drillData: drill,+ questions,+ score: localAccuracyScore(questions),+ totalMs: Date.now() - startedAtRef.current,+ });+ }, [drill, onComplete]);++ const finishRef = useRef(finish);+ finishRef.current = finish;++ useEffect(() => { trialStartRef.current = Date.now(); advancingRef.current = false; }, [trialIdx]);++ const answer = useCallback((optionIndex) => {+ if (advancingRef.current || feedback) return;+ const trial = trials[trialIdx];+ if (!trial) return;+ const correct = optionIndex === trial.correctIndex;+ answersRef.current[trialIdx] = {+ prompt: `shape ${trial.shape || ''}`,+ index: trialIdx,+ answered: optionIndex,+ correct,+ responseMs: Date.now() - trialStartRef.current,+ };+ const isLast = trialIdx + 1 >= trials.length;+ if (isTraining) {+ setFeedback({ correct, expected: trial.correctIndex, isLast });+ } else {+ advancingRef.current = true;+ if (isLast) finishRef.current(); else setTrialIdx(i => i + 1);+ }+ }, [feedback, trials, trialIdx, isTraining]);++ const acknowledge = useCallback(() => {+ const isLast = feedback?.isLast;+ setFeedback(null);+ if (isLast) finishRef.current(); else setTrialIdx(i => i + 1);+ }, [feedback]);++ // Number keys 1..N pick the matching option.+ useEffect(() => {+ const onKey = (e) => {+ if (feedback) { if (e.key === 'Enter') { e.preventDefault(); acknowledge(); } return; }+ const optionCount = trials[trialIdx]?.options?.length || 0;+ const idx = parseInt(e.key, 10) - 1;+ if (Number.isInteger(idx) && idx >= 0 && idx < optionCount) {+ e.preventDefault();+ answer(idx);+ }+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [feedback, trials, trialIdx, answer, acknowledge]);++ const trial = trials[trialIdx];+ const progressPct = trials.length > 0 ? (trialIdx / trials.length) * 100 : 0;++ return (+ <div className="max-w-lg mx-auto space-y-6">+ <DrillHeader type="mental-rotation" isTraining={isTraining} drillIndex={drillIndex} drillCount={drillCount} />++ <p className="text-center text-sm text-gray-400">+ Which shape below is the <span className="text-white font-medium">SAME</span> shape, just rotated — not mirrored?+ </p>++ {trial ? (+ <>+ <div className="flex justify-center py-4">+ <ShapeGrid cells={trial.target} size={gridSize} />+ </div>++ {feedback ? (+ <div className="space-y-4">+ <div className={`flex items-center justify-center gap-2 ${feedback.correct ? 'text-port-success' : 'text-port-error'}`}>+ {feedback.correct ? <Check size={24} /> : <X size={24} />}+ <span className="text-sm">{feedback.correct ? 'Correct' : `Option ${feedback.expected + 1} was the match`}</span>+ </div>+ <button+ onClick={acknowledge}+ autoFocus+ className="w-full px-6 py-3 bg-port-accent-2 hover:bg-port-accent-2/80 text-port-on-accent-2 font-medium rounded-lg transition-colors"+ >+ Next+ </button>+ </div>+ ) : (+ <div className="grid grid-cols-2 gap-3">+ {trial.options.map((cells, i) => (+ <button+ key={i}+ onClick={() => answer(i)}+ className="flex flex-col items-center gap-1 px-4 py-4 bg-port-card hover:bg-port-bg border border-port-border rounded-lg transition-colors"+ >+ <ShapeGrid cells={cells} size={gridSize} />+ <span className="text-xs text-gray-600">{i + 1}</span>+ </button>+ ))}+ </div>+ )}+ </>+ ) : (+ <div className="text-gray-500 text-center py-8">Done</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" style={{ width: `${progressPct}%` }} />+ </div>+ </div>+ </div>+ );+}++// =============================================================================+// REACTION TIME — simple (react ASAP) or choice (react to the lit target) RT+// =============================================================================+function ReactionTimeRunner({ drill, drillIndex, drillCount, onComplete, isTraining }) {+ const trials = drill.trials || [];+ const mode = drill.config?.mode === 'choice' ? 'choice' : 'simple';+ const choices = drill.config?.choices || 3;++ const [trialIdx, setTrialIdx] = useState(0);+ const [phase, setPhase] = useState('waiting'); // 'waiting' | 'go' | 'result'+ const [lastResult, setLastResult] = useState(null);+ const answersRef = useRef([]);+ const stimulusShownRef = useRef(false);+ const goStartRef = useRef(0);+ const startedAtRef = useRef(Date.now());+ const mountedRef = useRef(true);+ const timeoutRef = useRef(null);+ const advancingRef = useRef(false);++ useEffect(() => { mountedRef.current = true; return () => { mountedRef.current = false; clearTimeout(timeoutRef.current); }; }, []);++ const finish = useCallback(() => {+ const questions = answersRef.current.filter(Boolean);+ onComplete({+ module: 'cognitive',+ type: 'reaction-time',+ config: drill.config,+ drillData: drill,+ questions,+ score: localAccuracyScore(questions),+ totalMs: Date.now() - startedAtRef.current,+ });+ }, [drill, onComplete]);++ const finishRef = useRef(finish);+ finishRef.current = finish;++ // Arm each trial: wait `delayMs` (randomized server-side so onset can't be+ // anticipated), then reveal the stimulus.+ useEffect(() => {+ if (trialIdx >= trials.length) { finishRef.current(); return; }+ advancingRef.current = false;+ stimulusShownRef.current = false;+ setPhase('waiting');+ setLastResult(null);+ const delay = trials[trialIdx]?.delayMs || 1000;+ timeoutRef.current = setTimeout(() => {+ if (!mountedRef.current) return;+ stimulusShownRef.current = true;+ goStartRef.current = Date.now();+ setPhase('go');+ }, delay);+ return () => clearTimeout(timeoutRef.current);+ }, [trialIdx]);++ const recordAndAdvance = useCallback((result) => {+ if (advancingRef.current) return;+ advancingRef.current = true;+ answersRef.current[trialIdx] = {+ prompt: mode === 'choice' ? `target ${trials[trialIdx]?.target ?? ''}` : 'react',+ index: trialIdx,+ ...result,+ };+ setLastResult(result);+ setPhase('result');+ const isLast = trialIdx + 1 >= trials.length;+ timeoutRef.current = setTimeout(() => {+ if (!mountedRef.current) return;+ if (isLast) finishRef.current(); else setTrialIdx(i => i + 1);+ }, isTraining ? 900 : 500);+ }, [trialIdx, trials, mode, isTraining]);++ const respond = useCallback((choiceIndex) => {+ if (advancingRef.current) return;+ if (!stimulusShownRef.current) {+ recordAndAdvance({ answered: null, correct: false, responseMs: 0, falseStart: true });+ return;+ }+ const responseMs = Date.now() - goStartRef.current;+ if (mode === 'choice') {+ const target = trials[trialIdx]?.target;+ recordAndAdvance({ answered: choiceIndex, correct: choiceIndex === target, responseMs, falseStart: false });+ } else {+ recordAndAdvance({ answered: 'react', correct: true, responseMs, falseStart: false });+ }+ }, [mode, trialIdx, trials, recordAndAdvance]);++ // Space (simple mode) or number keys 1..N (choice mode) register a response.+ useEffect(() => {+ const onKey = (e) => {+ if (phase === 'result') return;+ if (mode === 'simple') {+ if (e.code === 'Space' || e.key === ' ' || e.key === 'Enter') { e.preventDefault(); respond(0); }+ } else {+ const idx = parseInt(e.key, 10) - 1;+ if (Number.isInteger(idx) && idx >= 0 && idx < choices) { e.preventDefault(); respond(idx); }+ }+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [phase, mode, choices, respond]);++ const progressPct = trials.length > 0 ? (trialIdx / trials.length) * 100 : 0;++ return (+ <div className="max-w-lg mx-auto space-y-6">+ <DrillHeader type="reaction-time" isTraining={isTraining} drillIndex={drillIndex} drillCount={drillCount} />++ <p className="text-center text-sm text-gray-400">+ {mode === 'choice'+ ? <>Wait for a target box to light up, then press its number — <span className="text-rose-400 font-semibold">as fast as you can</span>.</>+ : <>Wait for the signal, then press <span className="text-white font-medium">Space</span> (or tap) — <span className="text-rose-400 font-semibold">as fast as you can</span>.</>}+ </p>++ <div className="py-8 min-h-[10rem] flex flex-col items-center justify-center gap-4">+ {phase === 'waiting' && (+ <button+ type="button"+ onClick={() => respond(0)}+ aria-label="Wait for the signal"+ className="w-32 h-32 rounded-full bg-port-border/30 text-gray-500 text-sm flex items-center justify-center"+ >+ Wait…+ </button>+ )}++ {phase === 'go' && mode === 'simple' && (+ <button+ type="button"+ onClick={() => respond(0)}+ className="w-32 h-32 rounded-full bg-port-success/80 hover:bg-port-success text-white font-bold text-lg transition-colors"+ >+ GO!+ </button>+ )}++ {phase === 'go' && mode === 'choice' && (+ <div className="grid grid-cols-2 gap-3 w-full">+ {Array.from({ length: choices }, (_, i) => {+ const isTarget = i === trials[trialIdx]?.target;+ return (+ <button+ key={i}+ type="button"+ onClick={() => respond(i)}+ className={`flex items-center justify-center gap-2 px-4 py-6 rounded-lg border font-semibold transition-colors ${+ isTarget+ ? 'bg-port-success/80 hover:bg-port-success border-port-success text-white'+ : 'bg-port-card border-port-border text-gray-500'+ }`}+ >+ {i + 1}+ </button>+ );+ })}+ </div>+ )}++ {phase === 'result' && lastResult && (+ <div className={`flex flex-col items-center gap-2 ${lastResult.correct ? 'text-port-success' : 'text-port-error'}`}>+ {lastResult.correct ? <Check size={32} /> : <X size={32} />}+ <div className="text-sm">+ {lastResult.falseStart ? 'Too soon!' : lastResult.correct ? `${lastResult.responseMs}ms` : 'Wrong'}+ </div>+ </div>+ )}+ </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" style={{ width: `${progressPct}%` }} />+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/meatspace/post/PostDrillConfig.jsx b/client/src/components/meatspace/post/PostDrillConfig.jsxindex eef01e43ab..defd69a69a 100644--- a/client/src/components/meatspace/post/PostDrillConfig.jsx+++ b/client/src/components/meatspace/post/PostDrillConfig.jsx@@ -175,10 +175,43 @@ const COGNITIVE_DRILL_META = {],defaults: { enabled: true, count: 15, timeLimitSec: 60 },},+ 'schulte-table': {+ label: 'Schulte Table',+ desc: 'Scan a shuffled grid and tap 1, 2, 3... in order — visual attention & speed',+ fields: [+ { key: 'size', label: 'Grid Size (NxN)', type: 'number', min: 3, max: 7 },+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 10, max: 300 },+ ],+ defaults: { enabled: true, size: 5, timeLimitSec: 120 },+ },+ 'mental-rotation': {+ label: 'Mental Rotation',+ desc: 'Pick the shape that’s the same, just rotated — spatial reasoning',+ fields: [+ { key: 'count', label: 'Trials', type: 'number', min: 4, max: 20 },+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 10, max: 300 },+ ],+ defaults: { enabled: true, count: 8, timeLimitSec: 120 },+ },+ 'reaction-time': {+ label: 'Reaction Time',+ desc: 'React the instant a stimulus appears — processing speed baseline',+ fields: [+ { key: 'mode', label: 'Mode', type: 'select', options: [+ { value: 'simple', label: 'Simple' },+ { value: 'choice', label: 'Choice' },+ ] },+ { key: 'count', label: 'Trials', type: 'number', min: 5, max: 40 },+ { key: 'minDelayMs', label: 'Min Delay (ms)', type: 'number', min: 300, max: 5000 },+ { key: 'maxDelayMs', label: 'Max Delay (ms)', type: 'number', min: 300, max: 8000 },+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 10, max: 300 },+ ],+ defaults: { enabled: true, mode: 'simple', count: 15, minDelayMs: 1000, maxDelayMs: 3000, timeLimitSec: 90 },+ },};// String-valued cognitive config keys must NOT be coerced to Number on edit.-const COGNITIVE_STRING_FIELDS = new Set(['direction']);+const COGNITIVE_STRING_FIELDS = new Set(['direction', 'mode']);// 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 56b50c730b..b5130d9c76 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx@@ -52,8 +52,23 @@ export default function PostSessionLauncher({ config, recentSessions, stats, stamaxLength: cfg.maxLength,showMs: cfg.showMs,count: cfg.count,+ size: cfg.size,+ mode: cfg.mode,+ minDelayMs: cfg.minDelayMs,+ maxDelayMs: cfg.maxDelayMs,+ choices: cfg.choices,});+ // Short "at a glance" summary chip per cognitive drill type, shown next to+ // its label in the launcher sidebar.+ function cognitiveSummary(type, cfg) {+ if (type === 'n-back') return `${cfg.n ?? 2}-back`;+ if (type === 'digit-span') return `${cfg.startLength ?? 3}–${cfg.maxLength ?? 8}`;+ if (type === 'schulte-table') return `${cfg.size ?? 5}×${cfg.size ?? 5}`;+ if (type === 'reaction-time') return `${cfg.count ?? 15} trials (${cfg.mode ?? 'simple'})`;+ return cfg.count ? `${cfg.count} trials` : '';+ }+function buildCleanTags() {const cleanTags = {};for (const [k, v] of Object.entries(tags)) {@@ -484,7 +499,7 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta<div key={type} className="flex items-center justify-between text-sm"><span className="text-white">{DRILL_LABELS[type] || type}</span><span className="text-gray-500">- {type === 'n-back' ? `${cfg.n ?? 2}-back` : type === 'digit-span' ? `${cfg.startLength ?? 3}–${cfg.maxLength ?? 8}` : cfg.count ? `${cfg.count} trials` : ''}+ {cognitiveSummary(type, cfg)}{cfg.timeLimitSec ? ` · ${cfg.timeLimitSec}s` : ''}</span></div>diff --git a/client/src/components/meatspace/post/constants.js b/client/src/components/meatspace/post/constants.jsindex bd88a22d26..50f2c123d2 100644--- a/client/src/components/meatspace/post/constants.js+++ b/client/src/components/meatspace/post/constants.js@@ -2,7 +2,7 @@ export const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-flueexport const MEMORY_DRILL_TYPES = ['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'];+export const COGNITIVE_DRILL_TYPES = ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time'];// Drill types valid elsewhere but not yet supported by the POST runner.// These use answers[] arrays instead of expected and need dedicated runners.@@ -56,7 +56,7 @@ export const DOMAINS = {color: 'text-rose-400',bgColor: 'bg-rose-500/20',timeBudgetSec: 90,- drillTypes: ['n-back', 'digit-span', 'stroop'],+ drillTypes: ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time'],},};@@ -95,6 +95,9 @@ export const DRILL_LABELS = {'n-back': 'N-Back','digit-span': 'Digit Span','stroop': 'Stroop',+ 'schulte-table': 'Schulte Table',+ 'mental-rotation': 'Mental Rotation',+ 'reaction-time': 'Reaction Time',};// Human-readable label for a domain key. `other` collects drills whose typediff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex 9d0bf78c86..b69c5892d9 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -21,7 +21,10 @@ const questionResultSchema = z.object({expected: z.union([z.number(), z.string()]).optional(),answered: z.union([z.number(), z.string()]).nullable(),correct: z.boolean().optional(),- responseMs: z.number().min(0)+ responseMs: z.number().min(0),+ // 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()});// LLM drill response (text-based)@@ -69,7 +72,13 @@ const drillTypeConfigSchema = z.object({direction: z.enum(['forward', 'backward']).optional(),startLength: z.number().int().min(2).max(12).optional(),maxLength: z.number().int().min(2).max(14).optional(),- showMs: z.number().int().min(200).max(5000).optional()+ showMs: z.number().int().min(200).max(5000).optional(),+ // --- Cognitive drill knobs (schulte-table / mental-rotation / reaction-time) ---+ size: z.number().int().min(3).max(7).optional(),+ 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()});// Task result within a sessiondiff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex c218144793..4eb86c4e61 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -47,7 +47,10 @@ const DEFAULT_CONFIG = {drillTypes: {'n-back': { enabled: true, n: 2, length: 20, timeLimitSec: 90 },'digit-span': { enabled: true, direction: 'forward', startLength: 3, maxLength: 8, timeLimitSec: 120 },- 'stroop': { enabled: true, count: 15, timeLimitSec: 60 }+ 'stroop': { enabled: true, count: 15, timeLimitSec: 60 },+ 'schulte-table': { enabled: true, size: 5, timeLimitSec: 120 },+ 'mental-rotation': { enabled: true, count: 8, timeLimitSec: 120 },+ 'reaction-time': { enabled: true, mode: 'simple', count: 15, minDelayMs: 1000, maxDelayMs: 3000, timeLimitSec: 90 }}},sessionModules: ['mental-math'],@@ -367,6 +370,9 @@ export function generateDrill(type, config = {}) {case 'n-back':case 'digit-span':case 'stroop':+ case 'schulte-table':+ case 'mental-rotation':+ case 'reaction-time':return generateCognitiveDrill(type, config);default:return null;diff --git a/server/services/meatspacePostCognitive.js b/server/services/meatspacePostCognitive.jsindex c14ae9ed06..325c9be1b7 100644--- a/server/services/meatspacePostCognitive.js+++ b/server/services/meatspacePostCognitive.js@@ -2,9 +2,12 @@* MeatSpace POST — Deterministic Cognitive Drills** Pure generators + scorers for non-LLM cognitive-training exercises:- * - n-back (working memory) — signal when the current item matches N steps back- * - digit-span (working memory) — recall a shown digit sequence forward/backward- * - stroop (attention/inhibition) — name the INK color, not the word+ * - n-back (working memory) — signal when the current item matches N steps back+ * - digit-span (working memory) — recall a shown digit sequence forward/backward+ * - stroop (attention/inhibition) — name the INK color, not the word+ * - 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** 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@@ -15,7 +18,7 @@// 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'];+export const COGNITIVE_DRILL_TYPES = ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time'];const NBACK_LETTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];@@ -59,6 +62,58 @@ function accuracySpeedScore(recomputed, refMs) {return Math.min(100, Math.max(0, Math.round((correctRatio * 0.8 + speedBonus * 0.2) * 100)));}+// Fisher-Yates shuffle. Used by Schulte table cell placement and mental+// rotation option ordering — never a naive `sort(() => Math.random() - 0.5)`.+function shuffle(arr) {+ const out = [...arr];+ for (let i = out.length - 1; i > 0; i--) {+ const j = Math.floor(Math.random() * (i + 1));+ [out[i], out[j]] = [out[j], out[i]];+ }+ return out;+}++// --- Mental rotation: grid-cell shape helpers -------------------------------+// Four chiral pentomino footprints, each within a 4x4 box. Verified (see+// meatspacePostCognitive.test.js) that every rotation is distinct from every+// mirrored-rotation, AND all 4 rotations of each are themselves distinct —+// so "rotated match" vs "mirrored distractor" is always unambiguous and there+// are always 3 distinct mirrored candidates to fill the distractor slots.+// (The classic Z/S-pentomino was excluded: it has 180deg rotational symmetry,+// leaving only 2 distinct mirrored variants — not enough for 3 distractors.)+const ROTATION_SHAPES = {+ F: [[1, 0], [2, 0], [0, 1], [1, 1], [1, 2]],+ L: [[0, 0], [0, 1], [0, 2], [0, 3], [1, 3]],+ N: [[0, 0], [0, 1], [1, 1], [1, 2], [1, 3]],+ Y: [[1, 0], [0, 1], [1, 1], [1, 2], [1, 3]],+};++function normalizeCells(cells) {+ const minX = Math.min(...cells.map(([x]) => x));+ const minY = Math.min(...cells.map(([, y]) => y));+ return cells.map(([x, y]) => [x - minX, y - minY]).sort((a, b) => a[0] - b[0] || a[1] - b[1]);+}++// Rotate 90deg clockwise `times` times (0-3) around the origin, then+// re-normalize into the non-negative quadrant.+function rotateCells(cells, times) {+ let pts = cells;+ for (let t = 0; t < ((times % 4) + 4) % 4; t++) {+ pts = pts.map(([x, y]) => [y, -x]);+ }+ return normalizeCells(pts);+}++// Mirror across the vertical axis (flip x) — same footprint size, opposite+// chirality, so it looks similar but is not reachable by rotation alone.+function mirrorCells(cells) {+ return normalizeCells(cells.map(([x, y]) => [-x, y]));+}++function cellsKey(cells) {+ return cells.map(([x, y]) => `${x},${y}`).join('|');+}+// =============================================================================// GENERATORS// =============================================================================@@ -144,6 +199,85 @@ export function generateStroop(config = {}) {};}+/**+ * Schulte table: a size x size grid holding the numbers 1..size*size shuffled+ * into random cells. The player scans the grid and taps 1, 2, 3... in order —+ * pure visual-attention/scan-speed, no recall required.+ */+export function generateSchulteTable(config = {}) {+ const size = clampInt(config.size, 3, 7, 5);+ const total = size * size;+ const numbers = Array.from({ length: total }, (_, i) => i + 1);+ const cells = shuffle(numbers);+ return {+ type: 'schulte-table',+ config: { size, timeLimitSec: clampInt(config.timeLimitSec, 10, 600, 120) },+ cells,+ };+}++/**+ * Mental rotation: each trial shows a reference shape (an asymmetric+ * grid-cell footprint) and 4 candidate shapes — exactly one is the reference+ * rotated (0/90/180/270deg); the rest are mirrored (reflected) at a random+ * rotation, so they share a silhouette "feel" without being a true rotation+ * match. `correctIndex` is the answer key; scoring recomputes it independently+ * from `shape`/`rotationSteps`, never trusting the stored index round-trip.+ */+export function generateMentalRotation(config = {}) {+ const count = clampInt(config.count, 4, 20, 8);+ const shapeKeys = Object.keys(ROTATION_SHAPES);+ const trials = [];+ for (let i = 0; i < count; i++) {+ const shapeKey = pick(shapeKeys);+ const baseCells = ROTATION_SHAPES[shapeKey];+ const rotationSteps = 1 + Math.floor(Math.random() * 3); // 1-3 (nonzero: 90/180/270deg)+ const correctCells = rotateCells(baseCells, rotationSteps);++ const options = [{ cells: correctCells, isMatch: true }];+ let guard = 0;+ while (options.length < 4 && guard < 50) {+ guard++;+ const mirrored = mirrorCells(rotateCells(baseCells, Math.floor(Math.random() * 4)));+ const key = cellsKey(mirrored);+ if (options.some(o => cellsKey(o.cells) === key)) continue;+ options.push({ cells: mirrored, isMatch: false });+ }+ const shuffled = shuffle(options);+ const correctIndex = shuffled.findIndex(o => o.isMatch);++ trials.push({+ shape: shapeKey,+ target: normalizeCells(baseCells),+ options: shuffled.map(o => o.cells),+ correctIndex,+ });+ }+ return { type: 'mental-rotation', config: { count, gridSize: 4 }, trials };+}++/**+ * Reaction time: simple (react the instant a stimulus appears) or choice+ * (react to WHICH of `choices` stimuli appeared) RT baseline. Each trial's+ * `delayMs` is randomized so the stimulus onset can't be anticipated.+ */+export function generateReactionTime(config = {}) {+ const mode = config.mode === 'choice' ? 'choice' : 'simple';+ const count = clampInt(config.count, 5, 40, 15);+ const minDelayMs = clampInt(config.minDelayMs, 300, 5000, 1000);+ const maxDelayMs = Math.max(minDelayMs, clampInt(config.maxDelayMs, 300, 8000, 3000));+ const choices = mode === 'choice' ? clampInt(config.choices, 2, 4, 3) : 1;++ const trials = [];+ for (let i = 0; i < count; i++) {+ const delayMs = minDelayMs + Math.floor(Math.random() * (maxDelayMs - minDelayMs + 1));+ const trial = { delayMs };+ if (mode === 'choice') trial.target = Math.floor(Math.random() * choices);+ trials.push(trial);+ }+ return { type: 'reaction-time', config: { mode, count, minDelayMs, maxDelayMs, choices }, trials };+}+export function generateCognitiveDrill(type, config = {}) {switch (type) {case 'n-back':@@ -152,6 +286,12 @@ export function generateCognitiveDrill(type, config = {}) {return generateDigitSpan(config);case 'stroop':return generateStroop(config);+ case 'schulte-table':+ return generateSchulteTable(config);+ case 'mental-rotation':+ return generateMentalRotation(config);+ case 'reaction-time':+ return generateReactionTime(config);default:return null;}@@ -233,6 +373,85 @@ function scoreStroop(drillData, questions) {return { score: accuracySpeedScore(recomputed, refMs), questions: recomputed };}+// Schulte table: each question is one "find the next number" step, keyed by+// `index` (0-based position in the 1..N sequence). Reference response window+// scales with grid size — a bigger grid needs more scanning per step.+function scoreSchulteTable(drillData, questions) {+ const size = drillData?.config?.size || 5;+ const total = size * size;+ const refMs = 1000 + size * 500;+ const recomputed = questions.map(q => {+ const i = Number.isInteger(q.index) ? q.index : -1;+ const expected = i + 1;+ const answered = q.answered == null ? null : Number(q.answered);+ return {+ prompt: `${expected}`,+ index: i,+ expected,+ answered,+ correct: i >= 0 && i < total && answered === expected,+ responseMs: clampMs(q.responseMs, refMs),+ };+ });+ return { score: accuracySpeedScore(recomputed, refMs), questions: recomputed };+}++// Mental rotation: `index` selects the trial; `answered` is the option index+// (0-3) the player picked. Expected is recomputed from `trials[index]`, never+// trusted from the client round-trip.+function scoreMentalRotation(drillData, questions) {+ const trials = drillData?.trials || [];+ const refMs = 6000;+ const recomputed = questions.map(q => {+ const trial = trials[q.index] || {};+ const expected = Number.isInteger(trial.correctIndex) ? trial.correctIndex : null;+ const answered = q.answered == null ? null : Number(q.answered);+ return {+ prompt: q.prompt ?? `shape ${trial.shape ?? ''}`,+ index: q.index,+ expected,+ answered,+ correct: expected != null && answered === expected,+ responseMs: clampMs(q.responseMs, refMs),+ };+ });+ return { score: accuracySpeedScore(recomputed, refMs), questions: recomputed };+}++// Reaction time: 'simple' trials just need a clean (non-false-start) press;+// 'choice' trials must also match the lit target index. A `falseStart` (press+// before the stimulus appeared) is always wrong regardless of client claims.+function scoreReactionTime(drillData, questions) {+ const trials = drillData?.trials || [];+ const mode = drillData?.config?.mode === 'choice' ? 'choice' : 'simple';+ const refMs = mode === 'choice' ? 1200 : 600;+ const recomputed = questions.map(q => {+ const trial = trials[q.index] || {};+ const falseStart = q.falseStart === true;+ let expected;+ let answered;+ let correct;+ if (mode === 'choice') {+ expected = Number.isInteger(trial.target) ? String(trial.target) : null;+ answered = falseStart || q.answered == null ? null : String(q.answered);+ correct = !falseStart && expected != null && answered === expected;+ } else {+ expected = 'react';+ answered = falseStart ? 'false-start' : q.responseMs > 0 ? 'react' : null;+ correct = answered === 'react';+ }+ return {+ prompt: mode === 'choice' ? `target ${trial.target ?? ''}` : 'react',+ index: q.index,+ expected,+ answered,+ correct,+ responseMs: clampMs(q.responseMs, refMs * 3),+ };+ });+ return { score: accuracySpeedScore(recomputed, refMs), questions: recomputed };+}+/*** Rescore a completed cognitive drill from its generated `drillData` + the* player's per-trial `questions`. Returns `{ score, questions, span? }`.@@ -246,6 +465,12 @@ export function scoreCognitiveDrill(type, drillData, questions = []) {return scoreDigitSpan(drillData, list);case 'stroop':return scoreStroop(drillData, list);+ case 'schulte-table':+ return scoreSchulteTable(drillData, list);+ case 'mental-rotation':+ return scoreMentalRotation(drillData, list);+ case 'reaction-time':+ return scoreReactionTime(drillData, list);default:return { score: 0, questions: list };}diff --git a/server/services/meatspacePostCognitive.test.js b/server/services/meatspacePostCognitive.test.jsindex e7fce2e08a..27c8ce76e6 100644--- a/server/services/meatspacePostCognitive.test.js+++ b/server/services/meatspacePostCognitive.test.js@@ -5,6 +5,9 @@ import {generateNBack,generateDigitSpan,generateStroop,+ generateSchulteTable,+ generateMentalRotation,+ generateReactionTime,generateCognitiveDrill,scoreCognitiveDrill,} from './meatspacePostCognitive.js';@@ -59,11 +62,66 @@ describe('cognitive drill generators', () => {expect(generateCognitiveDrill('n-back').type).toBe('n-back');expect(generateCognitiveDrill('digit-span').type).toBe('digit-span');expect(generateCognitiveDrill('stroop').type).toBe('stroop');+ 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('nope')).toBeNull();});- it('exposes exactly the three shipped cognitive types', () => {- expect(COGNITIVE_DRILL_TYPES).toEqual(['n-back', 'digit-span', 'stroop']);+ 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('schulte-table shuffles 1..size*size into every cell exactly once', () => {+ const drill = generateSchulteTable({ size: 4 });+ expect(drill.type).toBe('schulte-table');+ expect(drill.config.size).toBe(4);+ expect(drill.cells).toHaveLength(16);+ expect([...drill.cells].sort((a, b) => a - b)).toEqual(Array.from({ length: 16 }, (_, i) => i + 1));+ });++ it('schulte-table clamps out-of-range size', () => {+ const drill = generateSchulteTable({ size: 100 });+ expect(drill.config.size).toBeLessThanOrEqual(7);+ const drill2 = generateSchulteTable({ size: 0 });+ expect(drill2.config.size).toBeGreaterThanOrEqual(3);+ });++ it('mental-rotation produces 4 options per trial with a valid correctIndex', () => {+ const drill = generateMentalRotation({ count: 6 });+ expect(drill.type).toBe('mental-rotation');+ expect(drill.trials).toHaveLength(6);+ for (const trial of drill.trials) {+ expect(trial.options).toHaveLength(4);+ expect(trial.correctIndex).toBeGreaterThanOrEqual(0);+ expect(trial.correctIndex).toBeLessThan(4);+ expect(Array.isArray(trial.target)).toBe(true);+ // Every option's cell count matches the base shape's (rotation/mirroring+ // preserve cell count) — a cheap sanity check that nothing was corrupted.+ for (const opt of trial.options) expect(opt.length).toBe(trial.target.length);+ }+ });++ it('reaction-time defaults to simple mode with no per-trial target', () => {+ const drill = generateReactionTime({ count: 5 });+ expect(drill.type).toBe('reaction-time');+ expect(drill.config.mode).toBe('simple');+ expect(drill.trials).toHaveLength(5);+ for (const trial of drill.trials) {+ expect(trial.target).toBeUndefined();+ expect(trial.delayMs).toBeGreaterThanOrEqual(drill.config.minDelayMs);+ expect(trial.delayMs).toBeLessThanOrEqual(drill.config.maxDelayMs);+ }+ });++ it('reaction-time choice mode assigns a target index within range', () => {+ const drill = generateReactionTime({ mode: 'choice', count: 8, choices: 4 });+ expect(drill.config.mode).toBe('choice');+ expect(drill.config.choices).toBe(4);+ for (const trial of drill.trials) {+ expect(trial.target).toBeGreaterThanOrEqual(0);+ expect(trial.target).toBeLessThan(4);+ }});});@@ -134,4 +192,58 @@ describe('cognitive drill scorers (recompute the answer key, never trust client)expect(result.score).toBe(0);expect(result.questions).toHaveLength(1);});++ it('schulte-table grades each "find the next number" step by expected position', () => {+ const drillData = { type: 'schulte-table', config: { size: 3 } };+ const { score, questions } = scoreCognitiveDrill('schulte-table', drillData, [+ { index: 0, answered: 1, responseMs: 500 }, // correct: expects 1+ { index: 1, answered: 3, responseMs: 500 }, // wrong: expects 2+ ]);+ expect(questions[0].correct).toBe(true);+ expect(questions[1].correct).toBe(false);+ expect(questions[1].expected).toBe(2);+ expect(score).toBeGreaterThan(0);+ expect(score).toBeLessThan(100);+ });++ it('mental-rotation recomputes the answer from trials[index].correctIndex, not client claims', () => {+ const drillData = {+ type: 'mental-rotation',+ trials: [+ { shape: 'F', correctIndex: 2 },+ { shape: 'L', correctIndex: 0 },+ ],+ };+ const { questions } = scoreCognitiveDrill('mental-rotation', drillData, [+ { index: 0, answered: 2, correct: false, responseMs: 3000 }, // client lied "false"; actually correct+ { index: 1, answered: 1, correct: true, responseMs: 3000 }, // client lied "true"; actually wrong+ ]);+ expect(questions[0].correct).toBe(true);+ expect(questions[1].correct).toBe(false);+ });++ it('reaction-time simple mode marks a false start wrong even with a fast responseMs', () => {+ const drillData = { type: 'reaction-time', config: { mode: 'simple' }, trials: [{ delayMs: 1000 }, { delayMs: 1000 }] };+ const { questions, score } = scoreCognitiveDrill('reaction-time', drillData, [+ { index: 0, answered: 'react', responseMs: 220, falseStart: false },+ { index: 1, answered: null, responseMs: 0, falseStart: true, correct: true }, // client lied "true"+ ]);+ expect(questions[0].correct).toBe(true);+ expect(questions[1].correct).toBe(false);+ expect(score).toBeGreaterThan(0);+ });++ it('reaction-time choice mode requires the answered index to match the trial target', () => {+ const drillData = { type: 'reaction-time', config: { mode: 'choice', choices: 3 }, trials: [{ delayMs: 800, target: 1 }] };+ const { questions } = scoreCognitiveDrill('reaction-time', drillData, [+ { index: 0, answered: 1, responseMs: 400 },+ ]);+ expect(questions[0].correct).toBe(true);+ expect(questions[0].expected).toBe('1');++ const wrong = scoreCognitiveDrill('reaction-time', drillData, [+ { index: 0, answered: 0, responseMs: 400 },+ ]);+ expect(wrong.questions[0].correct).toBe(false);+ });});