Skip to content

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

feat([issue-1993]): add N-Back, Digit Span & Stroop cognitive drills to POST

[._.]/ Adam Eivy4f3edaecd06c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 76cad2b521..d7b6a737a5 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,6 +24,7 @@
- **[issue-1988] POST History is now a responsive analytics dashboard.** The History view (`client/src/components/meatspace/post/PostHistory.jsx`) was a single `max-w-3xl` column that stacked a lone overall-score line chart, a 3-up stat block, and the session table — surfacing only a fraction of what `getPostStats` already computes. It now fills desktop width and surfaces the full stats payload: a 4-up summary of **Sessions / Avg Score / Current Streak / Longest Streak**, a wide **Score Trend** line beside a horizontal **Avg by Domain** bar chart (each domain colored to match its `text-*-400` domain class), and a **Drill Breakdown** card that groups every drill's average into per-domain progress bars — so per-domain and per-drill averages plus streaks are visible without opening a single session. The five training domains (Mental Math / Memory / Wordplay / Verbal Agility / Imagination) are derived from each drill's *type* via `DRILL_TO_DOMAIN`, because the runners persist coarse module keys (`mental-math`, `llm-drills`) rather than domain keys — so all LLM drills split correctly across Wordplay/Verbal/Imagination instead of collapsing into one bucket. Mobile stays single-column; the 7/30/90/All range selector still drives every panel from one fetch. (Closes #1988)
- **[issue-1989] POST Memory surfaces are now responsive.** The Memory Builder, Practice, and Session Results screens were all pinned to a single narrow `max-w-2xl` column that wasted desktop width. **Memory Builder** (`MemoryBuilder.jsx`) now renders its saved items as a responsive card grid (`grid-cols-1 md:grid-cols-2 xl:grid-cols-3`) — each card lays out the item icon, title, line/chunk meta, and mastery badge above a full-width Practice button (with an aria-labeled delete for non-built-ins), while the create form and description stay in a readable `max-w-2xl` column above the grid. **Memory Practice** (`MemoryPractice.jsx`) widens the reading-oriented screens to `max-w-4xl` — the practice-mode picker (now a two-column card grid), Learn progressive-reveal, and Speed Run — while the active-recall focus steps (Sequence, Fill-in-the-Blank, Spaced Repetition) stay at a comfortable `max-w-2xl` for readability. **Session Results** (`PostSessionResults.jsx`) widens to `max-w-4xl` and lays the per-drill breakdown out in two columns on desktop. Layout-only: create/edit/delete, practice submission, mastery display, and score/breakdown rendering are unchanged; every surface collapses to a single column on mobile. (Closes #1989)
- **[issue-1992] Opt-in adaptive difficulty for mental-math POST drills.** Math drill params (`steps` / `maxDigits` / `maxExponent` / estimation `tolerancePct`) were fixed values from config that never responded to how you were doing. A new **Adaptive difficulty** toggle in the Drill Configuration screen (default OFF, so existing installs are unchanged) makes each math drill nudge its primary difficulty knob from your recent scored performance: sustained high accuracy (≥90% over enough sessions) bumps it one step harder, repeated misses (≤50%) ease it back, all clamped to safe min/max bounds — and it won't move until it has enough scored samples to trust. The adjustment is a pure, unit-tested policy (`server/lib/postAdaptive.js`) applied server-side at drill-generation time, so manual config still wins whenever Adaptive is off. It's fully transparent: each math drill card shows the effective difficulty (e.g. "Adaptive: max digits 2 → 3 (harder · 94% recent)") via a new `GET /post/adaptive-preview` endpoint, so it's never a black box. (`server/lib/postAdaptive.js`, `server/services/meatspacePost.js`, `client/src/components/meatspace/post/PostDrillConfig.jsx`, Closes #1992)
+- **[issue-1993] New deterministic cognitive drills — N-Back, Digit Span, and Stroop.** POST spanned math, LLM, and memory drills but was missing classic non-LLM cognitive-training exercises. A new **Cognitive** domain adds three provider-free drills: **N-Back** (1/2/3-back working-memory matching), **Digit Span** (forward/backward sequence recall), and **Stroop** (name the ink color, not the word — attention/inhibition). Each is configurable in the Drill Configuration screen, playable in both Test and Train modes via a dedicated interactive runner, scored, and saved to your training history alongside every other drill — with **zero AI provider calls**. Scoring is recomputed server-side from the generated drill (never trusting the client) using a shared 80% accuracy + 20% speed blend, and the drills are picked up by Full POST and Quick 5 Min automatically. (Closes #1993)
## Media Generation
diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx
new file mode 100644
index 0000000000..b3f7f0e903
--- /dev/null
+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx
@@ -0,0 +1,500 @@
+import { useState, useEffect, useRef, useCallback } from 'react';
+import { Brain, Check, X } from 'lucide-react';
+import { DRILL_LABELS } from './constants';
+
+/**
+ * Interactive runner for deterministic cognitive drills (n-back, digit-span,
+ * stroop). Unlike the math/memory PostDrillRunner (single prompt → typed
+ * answer), these are timed, stimulus-driven flows, so each type has its own
+ * sub-runner. Every sub-runner assembles a full drill result — `{ module,
+ * type, config, drillData, questions, score, totalMs }` — and hands it to
+ * `onComplete`. The client score is a local estimate for the immediate results
+ * view; the server recomputes it deterministically from `drillData` on save
+ * (server/services/meatspacePostCognitive.js). NO provider calls anywhere.
+ */
+export default function PostCognitiveDrillRunner({ drill, timeLimitSec, drillIndex, drillCount, onComplete, isTraining }) {
+ if (!drill) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <div className="text-gray-400">Loading drill...</div>
+ </div>
+ );
+ }
+
+ const shared = { drill, drillIndex, drillCount, onComplete, isTraining };
+ switch (drill.type) {
+ case 'n-back':
+ return <NBackRunner {...shared} />;
+ case 'digit-span':
+ return <DigitSpanRunner {...shared} />;
+ case 'stroop':
+ return <StroopRunner {...shared} />;
+ default:
+ return <div className="text-port-error text-center py-8">Unsupported cognitive drill: {drill.type}</div>;
+ }
+}
+
+// Shared header: drill label + position within the session.
+function DrillHeader({ type, isTraining, drillIndex, drillCount }) {
+ return (
+ <div className="flex items-center justify-between text-sm text-gray-400">
+ <span className="flex items-center gap-1.5 text-rose-400">
+ <Brain size={14} />
+ {DRILL_LABELS[type] || type}
+ {isTraining && ' — Training'}
+ </span>
+ <span>Drill {drillIndex + 1} of {drillCount}</span>
+ </div>
+ );
+}
+
+function localAccuracyScore(questions) {
+ if (!questions.length) return 0;
+ const correct = questions.filter(q => q.correct).length;
+ return Math.round((correct / questions.length) * 100);
+}
+
+// =============================================================================
+// N-BACK — a letter stream; signal when the current letter matches N steps back
+// =============================================================================
+function NBackRunner({ drill, drillIndex, drillCount, onComplete, isTraining }) {
+ const seq = drill.sequence || [];
+ const n = drill.config?.n ?? 2;
+ const stimulusMs = drill.config?.stimulusMs || 2500;
+
+ const [pos, setPos] = useState(-1); // -1 = pre-roll
+ const [pressed, setPressed] = useState(false); // current stimulus registered a Match press
+ const answersRef = useRef(seq.map(() => ({ answered: null, responseMs: 0 })));
+ const stimStartRef = useRef(0);
+ const startedAtRef = useRef(Date.now());
+ const mountedRef = useRef(true);
+ const timeoutRef = useRef(null);
+
+ const finish = useCallback(() => {
+ const questions = seq
+ .map((letter, i) => ({ letter, i }))
+ .filter(({ i }) => i >= n)
+ .map(({ letter, i }) => {
+ const a = answersRef.current[i] || {};
+ const isTarget = seq[i] === seq[i - n];
+ const answeredMatch = a.answered === 'match';
+ return {
+ prompt: letter,
+ index: i,
+ answered: a.answered ?? null,
+ correct: answeredMatch === isTarget,
+ responseMs: a.responseMs || 0,
+ };
+ });
+ onComplete({
+ module: 'cognitive',
+ type: 'n-back',
+ config: drill.config,
+ drillData: drill,
+ questions,
+ score: localAccuracyScore(questions),
+ totalMs: Date.now() - startedAtRef.current,
+ });
+ }, [drill, seq, n, onComplete]);
+
+ const finishRef = useRef(finish);
+ finishRef.current = finish;
+
+ useEffect(() => {
+ mountedRef.current = true;
+ let i = 0;
+ const step = () => {
+ if (!mountedRef.current) return;
+ if (i >= seq.length) { finishRef.current(); return; }
+ const cur = i;
+ setPos(cur);
+ setPressed(false);
+ stimStartRef.current = Date.now();
+ timeoutRef.current = setTimeout(() => { i = cur + 1; step(); }, stimulusMs);
+ };
+ timeoutRef.current = setTimeout(step, 800);
+ return () => { mountedRef.current = false; clearTimeout(timeoutRef.current); };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const registerMatch = useCallback(() => {
+ setPos(curPos => {
+ if (curPos < n) return curPos;
+ const a = answersRef.current[curPos];
+ if (a && a.answered !== 'match') {
+ a.answered = 'match';
+ a.responseMs = Date.now() - stimStartRef.current;
+ setPressed(true);
+ }
+ return curPos;
+ });
+ }, [n]);
+
+ // Spacebar / Enter registers a match for the current stimulus.
+ useEffect(() => {
+ const onKey = (e) => {
+ if (e.code === 'Space' || e.key === ' ' || e.key === 'Enter') {
+ e.preventDefault();
+ registerMatch();
+ }
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [registerMatch]);
+
+ const decisionTotal = Math.max(0, seq.length - n);
+ const decisionDone = pos >= n ? pos - n : 0;
+ const progressPct = decisionTotal > 0 ? Math.min(100, (decisionDone / decisionTotal) * 100) : 0;
+ const active = pos >= 0 && pos < seq.length;
+
+ return (
+ <div className="max-w-lg mx-auto space-y-6">
+ <DrillHeader type="n-back" isTraining={isTraining} drillIndex={drillIndex} drillCount={drillCount} />
+
+ <p className="text-center text-sm text-gray-400">
+ Press <span className="text-white font-medium">Match</span> (or Space) when the letter matches the one{' '}
+ <span className="text-rose-400 font-semibold">{n}</span> step{n !== 1 ? 's' : ''} back.
+ </p>
+
+ <div className="text-center py-10">
+ {pos < 0 ? (
+ <div className="text-xl text-gray-500">Get ready…</div>
+ ) : (
+ <div className={`text-7xl font-mono font-bold transition-colors ${pressed ? 'text-rose-400' : 'text-white'}`}>
+ {seq[pos]}
+ </div>
+ )}
+ </div>
+
+ <button
+ type="button"
+ onClick={registerMatch}
+ disabled={!active || pos < n}
+ className="w-full px-6 py-4 bg-rose-500/20 hover:bg-rose-500/30 disabled:opacity-40 disabled:cursor-not-allowed text-rose-300 border border-rose-500/40 font-semibold rounded-lg transition-colors"
+ >
+ Match
+ </button>
+
+ <div className="space-y-1">
+ <div className="flex justify-between text-xs text-gray-500">
+ <span>{decisionDone} / {decisionTotal} decisions</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>
+ );
+}
+
+// =============================================================================
+// DIGIT SPAN — memorize a shown sequence, then recall it forward/backward
+// =============================================================================
+function DigitSpanRunner({ drill, drillIndex, drillCount, onComplete, isTraining }) {
+ const sequences = drill.sequences || [];
+ const direction = drill.config?.direction === 'backward' ? 'backward' : 'forward';
+ const showMs = drill.config?.showMs || 1000;
+
+ const [seqIdx, setSeqIdx] = useState(0);
+ const [phase, setPhase] = useState('show'); // 'show' | 'recall'
+ const [shownIdx, setShownIdx] = useState(-1); // which digit is visible (-1 blank)
+ const [input, setInput] = useState('');
+ const [feedback, setFeedback] = useState(null); // training-mode reveal
+ const answersRef = useRef([]);
+ const recallStartRef = useRef(0);
+ const startedAtRef = useRef(Date.now());
+ const mountedRef = useRef(true);
+ const inputRef = useRef(null);
+
+ const finish = useCallback(() => {
+ const questions = answersRef.current.filter(Boolean);
+ onComplete({
+ module: 'cognitive',
+ type: 'digit-span',
+ config: drill.config,
+ drillData: drill,
+ questions,
+ score: localAccuracyScore(questions),
+ totalMs: Date.now() - startedAtRef.current,
+ });
+ }, [drill, onComplete]);
+
+ const finishRef = useRef(finish);
+ finishRef.current = finish;
+
+ useEffect(() => { mountedRef.current = true; return () => { mountedRef.current = false; }; }, []);
+
+ // Reveal the current sequence one digit at a time, then switch to recall.
+ useEffect(() => {
+ if (seqIdx >= sequences.length) { finishRef.current(); return; }
+ setPhase('show');
+ setInput('');
+ setFeedback(null);
+ setShownIdx(-1);
+ const digits = sequences[seqIdx].digits || [];
+ const gap = 200;
+ const timers = [];
+ let t = 600;
+ digits.forEach((_, di) => {
+ timers.push(setTimeout(() => { if (mountedRef.current) setShownIdx(di); }, t));
+ t += showMs;
+ timers.push(setTimeout(() => { if (mountedRef.current) setShownIdx(-1); }, t));
+ t += gap;
+ });
+ timers.push(setTimeout(() => {
+ if (!mountedRef.current) return;
+ setPhase('recall');
+ recallStartRef.current = Date.now();
+ }, t));
+ return () => timers.forEach(clearTimeout);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [seqIdx]);
+
+ useEffect(() => { if (phase === 'recall') inputRef.current?.focus(); }, [phase]);
+
+ const advance = useCallback((answeredStr) => {
+ const digits = sequences[seqIdx].digits || [];
+ const ordered = direction === 'backward' ? [...digits].reverse() : digits;
+ const expected = ordered.join('');
+ const answered = (answeredStr || '').replace(/\D/g, '');
+ answersRef.current[seqIdx] = {
+ prompt: `${digits.length}-digit (${direction})`,
+ index: seqIdx,
+ answered: answered.length ? answered : null,
+ correct: answered.length > 0 && answered === expected,
+ responseMs: Date.now() - recallStartRef.current,
+ length: digits.length,
+ };
+ if (isTraining) {
+ setFeedback({ expected, answered, correct: answered.length > 0 && answered === expected });
+ } else {
+ setSeqIdx(i => i + 1);
+ }
+ }, [sequences, seqIdx, direction, isTraining]);
+
+ const handleSubmit = (e) => {
+ e.preventDefault();
+ if (phase !== 'recall' || feedback) return;
+ advance(input);
+ };
+
+ const digits = sequences[seqIdx]?.digits || [];
+ const progressPct = sequences.length > 0 ? (seqIdx / sequences.length) * 100 : 0;
+
+ return (
+ <div className="max-w-lg mx-auto space-y-6">
+ <DrillHeader type="digit-span" isTraining={isTraining} drillIndex={drillIndex} drillCount={drillCount} />
+
+ <p className="text-center text-sm text-gray-400">
+ Memorize the digits, then type them{' '}
+ <span className="text-rose-400 font-semibold">{direction === 'backward' ? 'in reverse' : 'in order'}</span>.
+ </p>
+
+ <div className="text-center py-10 min-h-[8rem] flex items-center justify-center">
+ {phase === 'show' ? (
+ <div className="text-7xl font-mono font-bold text-white tabular-nums">
+ {shownIdx >= 0 ? digits[shownIdx] : ''}
+ </div>
+ ) : feedback ? (
+ <div className="flex flex-col items-center gap-2">
+ {feedback.correct
+ ? <Check size={40} className="text-port-success" />
+ : <X size={40} className="text-port-error" />}
+ <div className="text-sm text-gray-400">Expected</div>
+ <div className="text-3xl font-mono font-bold text-port-success tracking-widest">{feedback.expected}</div>
+ {!feedback.correct && feedback.answered && (
+ <div className="text-lg font-mono text-port-error line-through">{feedback.answered}</div>
+ )}
+ </div>
+ ) : (
+ <div className="text-xl text-gray-500">Recall the {direction === 'backward' ? 'reversed ' : ''}sequence</div>
+ )}
+ </div>
+
+ {phase === 'recall' && !feedback && (
+ <form onSubmit={handleSubmit} className="flex gap-3">
+ <input
+ ref={inputRef}
+ type="text"
+ inputMode="numeric"
+ pattern="[0-9]*"
+ value={input}
+ onChange={e => setInput(e.target.value.replace(/\D/g, ''))}
+ placeholder="Digits"
+ autoFocus
+ className="flex-1 bg-port-bg border border-port-border rounded-lg px-4 py-3 text-2xl font-mono text-white text-center tracking-widest placeholder-gray-600 focus:border-rose-400 focus:outline-none"
+ />
+ <button type="submit" className="px-6 py-3 bg-rose-500/20 hover:bg-rose-500/30 text-rose-300 border border-rose-500/40 font-medium rounded-lg transition-colors">
+ Enter
+ </button>
+ </form>
+ )}
+
+ {phase === 'recall' && !feedback && (
+ <div className="text-center">
+ <button onClick={() => advance('')} className="text-sm text-gray-500 hover:text-gray-300 transition-colors">
+ Skip
+ </button>
+ </div>
+ )}
+
+ {feedback && (
+ <button
+ onClick={() => setSeqIdx(i => i + 1)}
+ 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 className="space-y-1">
+ <div className="flex justify-between text-xs text-gray-500">
+ <span>Round {Math.min(seqIdx + 1, sequences.length)} of {sequences.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>
+ );
+}
+
+// =============================================================================
+// STROOP — name the INK color of a color-word (ignore what the word says)
+// =============================================================================
+function StroopRunner({ drill, drillIndex, drillCount, onComplete, isTraining }) {
+ const trials = drill.trials || [];
+ const options = drill.options || [];
+
+ const [trialIdx, setTrialIdx] = useState(0);
+ const [feedback, setFeedback] = useState(null); // { correct } 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: 'stroop',
+ 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((colorName) => {
+ if (advancingRef.current || feedback) return;
+ const trial = trials[trialIdx];
+ if (!trial) return;
+ const correct = colorName === trial.inkColor;
+ answersRef.current[trialIdx] = {
+ prompt: trial.word,
+ index: trialIdx,
+ answered: colorName,
+ correct,
+ responseMs: Date.now() - trialStartRef.current,
+ };
+ const isLast = trialIdx + 1 >= trials.length;
+ if (isTraining) {
+ setFeedback({ correct, expected: trial.inkColor, 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 idx = parseInt(e.key, 10) - 1;
+ if (Number.isInteger(idx) && idx >= 0 && idx < options.length) {
+ e.preventDefault();
+ answer(options[idx].name);
+ }
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [feedback, options, 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="stroop" isTraining={isTraining} drillIndex={drillIndex} drillCount={drillCount} />
+
+ <p className="text-center text-sm text-gray-400">
+ Tap the <span className="text-white font-medium">ink color</span> of the word — not what it spells.
+ </p>
+
+ <div className="text-center py-12 min-h-[8rem] flex items-center justify-center">
+ {trial ? (
+ <div className="text-6xl font-bold uppercase tracking-wide" style={{ color: trial.inkHex }}>
+ {trial.word}
+ </div>
+ ) : (
+ <div className="text-gray-500">Done</div>
+ )}
+ </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' : `Ink was ${feedback.expected}`}</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">
+ {options.map((opt, i) => (
+ <button
+ key={opt.name}
+ onClick={() => answer(opt.name)}
+ className="flex items-center justify-center gap-2 px-4 py-4 bg-port-card hover:bg-port-bg border border-port-border rounded-lg text-white font-medium capitalize transition-colors"
+ >
+ <span className="w-4 h-4 rounded-full" style={{ backgroundColor: opt.hex }} aria-hidden="true" />
+ {opt.name}
+ <span className="text-xs text-gray-600">{i + 1}</span>
+ </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" style={{ width: `${progressPct}%` }} />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/meatspace/post/PostDrillConfig.jsx b/client/src/components/meatspace/post/PostDrillConfig.jsx
index b4ddc3f91a..eef01e43ab 100644
--- a/client/src/components/meatspace/post/PostDrillConfig.jsx
+++ b/client/src/components/meatspace/post/PostDrillConfig.jsx
@@ -137,6 +137,62 @@ function seedLlmDrillTypes(saved) {
return out;
}
+// Deterministic cognitive drills (no LLM). Field ranges mirror the server
+// clamps in server/services/meatspacePostCognitive.js and the Zod bounds in
+// server/lib/postValidation.js. `defaults` mirror the server DEFAULT_CONFIG so
+// the launcher and generators agree.
+const COGNITIVE_DRILL_META = {
+ 'n-back': {
+ label: 'N-Back',
+ desc: 'Signal when a letter matches the one N steps back — working memory',
+ fields: [
+ { key: 'n', label: 'N (steps back)', type: 'number', min: 1, max: 3 },
+ { key: 'length', label: 'Sequence Length', type: 'number', min: 6, max: 60 },
+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 10, max: 300 },
+ ],
+ defaults: { enabled: true, n: 2, length: 20, timeLimitSec: 90 },
+ },
+ 'digit-span': {
+ label: 'Digit Span',
+ desc: 'Recall a shown digit sequence forward or backward',
+ fields: [
+ { key: 'direction', label: 'Direction', type: 'select', options: [
+ { value: 'forward', label: 'Forward' },
+ { value: 'backward', label: 'Backward' },
+ ] },
+ { key: 'startLength', label: 'Start Length', type: 'number', min: 2, max: 12 },
+ { key: 'maxLength', label: 'Max Length', type: 'number', min: 2, max: 14 },
+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 10, max: 300 },
+ ],
+ defaults: { enabled: true, direction: 'forward', startLength: 3, maxLength: 8, timeLimitSec: 120 },
+ },
+ 'stroop': {
+ label: 'Stroop',
+ desc: 'Name the ink color of a color-word — attention & inhibition',
+ fields: [
+ { key: 'count', label: 'Trials', type: 'number', min: 5, max: 40 },
+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 10, max: 300 },
+ ],
+ defaults: { enabled: true, count: 15, timeLimitSec: 60 },
+ },
+};
+
+// String-valued cognitive config keys must NOT be coerced to Number on edit.
+const COGNITIVE_STRING_FIELDS = new Set(['direction']);
+
+// Seed every cognitive drill type so a card's toggle reflects real, persistable
+// state — same enabled-by-presence convention as seedLlmDrillTypes.
+function seedCognitiveDrillTypes(saved) {
+ const out = {};
+ for (const [type, meta] of Object.entries(COGNITIVE_DRILL_META)) {
+ const savedEntry = saved?.[type];
+ out[type] = savedEntry
+ ? { ...meta.defaults, ...savedEntry, enabled: savedEntry.enabled !== false }
+ : { ...meta.defaults };
+ }
+ return out;
+}
+
// LLM drills grouped by their DOMAINS key for section-headered rendering.
const LLM_DRILL_GROUPS = [
{ key: 'wordplay', label: 'Wordplay', types: ['pun-wordplay', 'word-association', 'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist'] },
@@ -192,14 +248,26 @@ function DrillCard({ meta, drillConfig, enabled, accent, onToggle, onUpdateField
{meta.fields.map(field => (
<div key={field.key}>
<label className="text-xs text-gray-500 mb-1 block">{field.label}</label>
- <input
- type="number"
- min={field.min}
- max={field.max}
- value={drillConfig[field.key] ?? ''}
- onChange={e => onUpdateField(field.key, e.target.value)}
- className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none"
- />
+ {field.type === 'select' ? (
+ <select
+ value={drillConfig[field.key] ?? field.options?.[0]?.value ?? ''}
+ onChange={e => onUpdateField(field.key, e.target.value)}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none"
+ >
+ {(field.options || []).map(opt => (
+ <option key={opt.value} value={opt.value}>{opt.label}</option>
+ ))}
+ </select>
+ ) : (
+ <input
+ type="number"
+ min={field.min}
+ max={field.max}
+ value={drillConfig[field.key] ?? ''}
+ onChange={e => onUpdateField(field.key, e.target.value)}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none"
+ />
+ )}
</div>
))}
</div>
@@ -226,6 +294,12 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {
const [llmModel, setLlmModel] = useState(
() => config?.llmDrills?.model || ''
);
+ const [cognitiveDrillTypes, setCognitiveDrillTypes] = useState(
+ () => seedCognitiveDrillTypes(config?.cognitive?.drillTypes)
+ );
+ const [cognitiveEnabled, setCognitiveEnabled] = useState(
+ () => config?.cognitive?.enabled !== false
+ );
const [adaptiveEnabled, setAdaptiveEnabled] = useState(
() => config?.adaptive?.enabled === true
);
@@ -284,6 +358,26 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {
}));
}
+ function toggleCognitiveDrill(type) {
+ setCognitiveDrillTypes(prev => ({
+ ...prev,
+ [type]: { ...prev[type], enabled: !(prev[type]?.enabled !== false) }
+ }));
+ }
+
+ function updateCognitiveField(type, key, value) {
+ let coerced;
+ if (COGNITIVE_STRING_FIELDS.has(key)) {
+ coerced = value || undefined;
+ } else {
+ coerced = value === '' || value === null || value === undefined ? undefined : Number(value);
+ }
+ setCognitiveDrillTypes(prev => ({
+ ...prev,
+ [type]: { ...prev[type], [key]: coerced }
+ }));
+ }
+
const selectedProvider = providers.find(p => p.id === llmProviderId);
const availableModels = filterSelectableModels(selectedProvider?.models);
@@ -292,6 +386,10 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {
const updated = await updatePostConfig({
mentalMath: { drillTypes },
adaptive: { enabled: adaptiveEnabled },
+ cognitive: {
+ enabled: cognitiveEnabled,
+ drillTypes: cognitiveDrillTypes
+ },
llmDrills: {
enabled: llmEnabled,
providerId: llmProviderId || null,
@@ -374,6 +472,47 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {
</div>
</div>
+ {/* Cognitive Drills Section (deterministic — no provider) */}
+ <div className="flex items-center justify-between pt-2">
+ <div className="flex items-center gap-2">
+ <Brain size={16} className="text-rose-400" />
+ <h3 className="text-sm font-medium text-gray-500 uppercase tracking-wider">Cognitive (deterministic)</h3>
+ </div>
+ <button
+ type="button"
+ role="switch"
+ aria-checked={cognitiveEnabled}
+ aria-label="Cognitive drills"
+ onClick={() => setCognitiveEnabled(!cognitiveEnabled)}
+ className={`shrink-0 w-10 h-5 rounded-full transition-colors relative ${
+ cognitiveEnabled ? 'bg-rose-400' : 'bg-port-border'
+ }`}
+ >
+ <div className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${
+ cognitiveEnabled ? 'translate-x-5' : 'translate-x-0.5'
+ }`} />
+ </button>
+ </div>
+
+ {cognitiveEnabled && (
+ <div className={CARD_GRID}>
+ {Object.entries(COGNITIVE_DRILL_META).map(([type, meta]) => {
+ const drillConfig = cognitiveDrillTypes[type] || {};
+ return (
+ <DrillCard
+ key={type}
+ meta={meta}
+ drillConfig={drillConfig}
+ enabled={drillConfig.enabled !== false}
+ accent="accent"
+ onToggle={() => toggleCognitiveDrill(type)}
+ onUpdateField={(key, value) => updateCognitiveField(type, key, value)}
+ />
+ );
+ })}
+ </div>
+ )}
+
{/* LLM Drills Section */}
<div className="flex items-center justify-between pt-2">
<div className="flex items-center gap-2">
diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsx
index 20b4b1009c..56b50c730b 100644
--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx
+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx
@@ -37,6 +37,23 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
const llmProviderId = config.llmDrills?.providerId || null;
const llmModel = config.llmDrills?.model || null;
+ // Deterministic cognitive drills (n-back / digit-span / stroop). No provider.
+ const enabledCognitiveDrills = config.cognitive?.enabled !== false
+ ? Object.entries(config.cognitive?.drillTypes || {}).filter(([, cfg]) => cfg.enabled !== false)
+ : [];
+
+ // Only the fields each cognitive generator reads; extras are harmless.
+ const cognitiveDrillConfig = (cfg) => ({
+ n: cfg.n,
+ length: cfg.length,
+ stimulusMs: cfg.stimulusMs,
+ direction: cfg.direction,
+ startLength: cfg.startLength,
+ maxLength: cfg.maxLength,
+ showMs: cfg.showMs,
+ count: cfg.count,
+ });
+
function buildCleanTags() {
const cleanTags = {};
for (const [k, v] of Object.entries(tags)) {
@@ -69,7 +86,13 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
model: cfg.model || llmModel
}));
- const drillConfigs = [...mathConfigs, ...llmConfigs];
+ const cognitiveConfigs = enabledCognitiveDrills.map(([type, cfg]) => ({
+ type,
+ config: cognitiveDrillConfig(cfg),
+ timeLimitSec: cfg.timeLimitSec || 90
+ }));
+
+ const drillConfigs = [...mathConfigs, ...llmConfigs, ...cognitiveConfigs];
onStart(drillConfigs, buildCleanTags(), mode === 'train');
}
@@ -77,6 +100,7 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
const allEnabledDrills = [
...enabledMathDrills.map(([type, cfg]) => ({ type, cfg, source: 'math' })),
...enabledLlmDrills.map(([type, cfg]) => ({ type, cfg, source: 'llm' })),
+ ...enabledCognitiveDrills.map(([type, cfg]) => ({ type, cfg, source: 'cognitive' })),
];
const enabledDomains = {};
@@ -95,21 +119,29 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
const pick = drills[Math.floor(Math.random() * drills.length)];
const cfg = pick.cfg;
+ let quickConfig;
+ if (pick.source === 'math') {
+ quickConfig = {
+ steps: cfg.steps,
+ count: cfg.count ? Math.min(cfg.count, 5) : undefined,
+ maxDigits: cfg.maxDigits,
+ subtrahend: cfg.subtrahend,
+ startRange: cfg.startRange,
+ bases: cfg.bases,
+ maxExponent: cfg.maxExponent,
+ tolerancePct: cfg.tolerancePct,
+ };
+ } else if (pick.source === 'cognitive') {
+ // Keep the drill short for a balanced 5-minute session.
+ quickConfig = { ...cognitiveDrillConfig(cfg), count: cfg.count ? Math.min(cfg.count, 10) : undefined };
+ } else {
+ quickConfig = { count: Math.min(cfg.count || 5, 3) }; // Fewer prompts for quick session
+ }
+
const drillConfig = {
type: pick.type,
domain: domainKey,
- config: pick.source === 'math'
- ? {
- steps: cfg.steps,
- count: cfg.count ? Math.min(cfg.count, 5) : undefined,
- maxDigits: cfg.maxDigits,
- subtrahend: cfg.subtrahend,
- startRange: cfg.startRange,
- bases: cfg.bases,
- maxExponent: cfg.maxExponent,
- tolerancePct: cfg.tolerancePct,
- }
- : { count: Math.min(cfg.count || 5, 3) }, // Fewer prompts for quick session
+ config: quickConfig,
timeLimitSec: domain.timeBudgetSec,
};
@@ -132,21 +164,27 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
if (!drills || drills.length === 0) return;
const domain = DOMAINS[domainKey];
const drillConfigs = drills.map(({ type, cfg, source }) => {
+ let focusConfig;
+ if (source === 'math') {
+ focusConfig = {
+ steps: cfg.steps,
+ count: cfg.count,
+ maxDigits: cfg.maxDigits,
+ subtrahend: cfg.subtrahend,
+ startRange: cfg.startRange,
+ bases: cfg.bases,
+ maxExponent: cfg.maxExponent,
+ tolerancePct: cfg.tolerancePct,
+ };
+ } else if (source === 'cognitive') {
+ focusConfig = cognitiveDrillConfig(cfg);
+ } else {
+ focusConfig = { count: cfg.count || 5 };
+ }
const drillConfig = {
type,
domain: domainKey,
- config: source === 'math'
- ? {
- steps: cfg.steps,
- count: cfg.count,
- maxDigits: cfg.maxDigits,
- subtrahend: cfg.subtrahend,
- startRange: cfg.startRange,
- bases: cfg.bases,
- maxExponent: cfg.maxExponent,
- tolerancePct: cfg.tolerancePct,
- }
- : { count: cfg.count || 5 },
+ config: focusConfig,
timeLimitSec: cfg.timeLimitSec || domain?.timeBudgetSec || 120,
};
if (source === 'llm') {
@@ -158,7 +196,7 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
onStart(drillConfigs, buildCleanTags(), mode === 'train');
}
- const hasAnyDrills = enabledMathDrills.length > 0 || enabledLlmDrills.length > 0;
+ const hasAnyDrills = enabledMathDrills.length > 0 || enabledLlmDrills.length > 0 || enabledCognitiveDrills.length > 0;
const domainCount = Object.keys(enabledDomains).length;
// Analytics derived from the 30-day stats window. Streaks span all history.
@@ -434,6 +472,27 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
</div>
)}
+ {/* Cognitive Drills (deterministic — no provider) */}
+ {enabledCognitiveDrills.length > 0 && (
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <div className="flex items-center gap-2 mb-3">
+ <Brain size={14} className="text-rose-400" />
+ <h3 className="text-sm font-medium text-gray-400">Cognitive</h3>
+ </div>
+ <div className="space-y-2">
+ {enabledCognitiveDrills.map(([type, cfg]) => (
+ <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` : ''}
+ {cfg.timeLimitSec ? ` · ${cfg.timeLimitSec}s` : ''}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
{!hasAnyDrills && (
<div className="bg-port-card border border-port-border rounded-lg p-4">
<p className="text-gray-500 text-sm">No drills enabled. Configure drills to get started.</p>
diff --git a/client/src/components/meatspace/post/constants.js b/client/src/components/meatspace/post/constants.js
index 054e3fd310..bd88a22d26 100644
--- a/client/src/components/meatspace/post/constants.js
+++ b/client/src/components/meatspace/post/constants.js
@@ -1,5 +1,8 @@
export const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay', 'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist', 'what-if', 'alternative-uses', 'story-prompt', 'invention-pitch', 'reframe'];
export 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'];
// Drill types valid elsewhere but not yet supported by the POST runner.
// These use answers[] arrays instead of expected and need dedicated runners.
@@ -47,6 +50,14 @@ export const DOMAINS = {
timeBudgetSec: 60,
drillTypes: ['what-if', 'alternative-uses', 'story-prompt', 'invention-pitch', 'reframe'],
},
+ cognitive: {
+ label: 'Cognitive',
+ icon: 'Brain',
+ color: 'text-rose-400',
+ bgColor: 'bg-rose-500/20',
+ timeBudgetSec: 90,
+ drillTypes: ['n-back', 'digit-span', 'stroop'],
+ },
};
// Map drill type → domain key
@@ -81,6 +92,9 @@ export const DRILL_LABELS = {
'story-prompt': 'Story Prompt',
'invention-pitch': 'Invention Pitch',
'reframe': 'Reframe',
+ 'n-back': 'N-Back',
+ 'digit-span': 'Digit Span',
+ 'stroop': 'Stroop',
};
// Human-readable label for a domain key. `other` collects drills whose type
diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsx
index 460c59ccb5..a50e4c942a 100644
--- a/client/src/components/meatspace/tabs/PostTab.jsx
+++ b/client/src/components/meatspace/tabs/PostTab.jsx
@@ -6,6 +6,7 @@ import { usePostSession } from '../../../hooks/usePostSession';
import PostSessionLauncher from '../post/PostSessionLauncher';
import PostDrillRunner from '../post/PostDrillRunner';
import PostLlmDrillRunner from '../post/PostLlmDrillRunner';
+import PostCognitiveDrillRunner from '../post/PostCognitiveDrillRunner';
import PostSessionResults from '../post/PostSessionResults';
import PostHistory from '../post/PostHistory';
import PostDrillConfig from '../post/PostDrillConfig';
@@ -14,7 +15,7 @@ import ElementsSong from '../post/ElementsSong';
import DrillTransition from '../post/DrillTransition';
import WordplayTrainer from '../post/WordplayTrainer';
import MorseTrainer from '../post/MorseTrainer';
-import { LLM_DRILL_TYPES } from '../post/constants';
+import { LLM_DRILL_TYPES, COGNITIVE_DRILL_TYPES } from '../post/constants';
export default function PostTab({ tab = 'launcher', subtab }) {
const navigate = useNavigate();
@@ -78,9 +79,9 @@ export default function PostTab({ tab = 'launcher', subtab }) {
}, [session.state, sessionView]);
const currentDrillConfig = session.drills[session.currentDrillIndex];
- const isLlmDrill = currentDrillConfig
- ? LLM_DRILL_TYPES.includes(currentDrillConfig.type)
- : session.currentDrill && LLM_DRILL_TYPES.includes(session.currentDrill.type);
+ const activeType = currentDrillConfig?.type || session.currentDrill?.type;
+ const isLlmDrill = activeType ? LLM_DRILL_TYPES.includes(activeType) : false;
+ const isCognitiveDrill = activeType ? COGNITIVE_DRILL_TYPES.includes(activeType) : false;
// Ephemeral session views overlay the launcher tab
if (tab === 'launcher' && sessionView) {
@@ -101,7 +102,7 @@ export default function PostTab({ tab = 'launcher', subtab }) {
}
if (sessionView === 'running') {
- if (session.state === 'loading' && isLlmDrill) {
+ if (session.state === 'loading' && (isLlmDrill || isCognitiveDrill)) {
return (
<div className="flex flex-col items-center justify-center h-64 gap-3">
<Loader size={32} className="text-port-accent-2 animate-spin" />
@@ -123,6 +124,18 @@ export default function PostTab({ tab = 'launcher', subtab }) {
/>
);
}
+ if (isCognitiveDrill) {
+ return (
+ <PostCognitiveDrillRunner
+ drill={session.currentDrill}
+ timeLimitSec={session.currentDrill?.timeLimitSec}
+ drillIndex={session.currentDrillIndex}
+ drillCount={session.drillCount}
+ onComplete={session.completeCognitiveDrill}
+ isTraining={session.isTraining}
+ />
+ );
+ }
return <PostDrillRunner session={session} />;
}
diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.js
index 8ad2b8a995..4ebb57ea79 100644
--- a/client/src/hooks/usePostSession.js
+++ b/client/src/hooks/usePostSession.js
@@ -270,6 +270,23 @@ export function usePostSession() {
}
}, [drillResults, currentDrillIndex, drills]);
+ // Interactive cognitive drills (n-back / digit-span / stroop) build their own
+ // fully-formed result (questions + local score) and hand it back here. Unlike
+ // LLM drills there is no async scoring call — the server recomputes the score
+ // deterministically from drillData on submit. Mirrors completeLlmDrill's
+ // advance/complete bookkeeping.
+ const completeCognitiveDrill = useCallback((drillResult) => {
+ const newResults = [...drillResults, drillResult];
+ setDrillResults(newResults);
+
+ if (currentDrillIndex + 1 < drills.length) {
+ setState(STATES.BETWEEN_DRILLS);
+ } else {
+ setSessionScore(computeSessionScoreFromResults(newResults));
+ setState(STATES.COMPLETE);
+ }
+ }, [drillResults, currentDrillIndex, drills]);
+
const saveSession = useCallback(async (tags = {}) => {
setState(STATES.SAVING);
@@ -343,6 +360,7 @@ export function usePostSession() {
nextDrill,
timeExpired,
completeLlmDrill,
+ completeCognitiveDrill,
saveSession,
reset
};
diff --git a/server/lib/postValidation.js b/server/lib/postValidation.js
index c76d73c5fb..6abe03ced1 100644
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@ -1,5 +1,6 @@
import { z } from 'zod';
import { CACHEABLE_TYPES } from '../services/meatspacePostDrillCache.js';
+import { COGNITIVE_DRILL_TYPES } from '../services/meatspacePostCognitive.js';
// =============================================================================
// POST (Power On Self Test) VALIDATION SCHEMAS
@@ -13,6 +14,10 @@ export const postTagsSchema = z.record(z.string().max(200));
// Memory: client scores with string comparison (text values)
const questionResultSchema = z.object({
prompt: z.string(),
+ // Cognitive drills key each trial back to its position in the generated
+ // drillData (n-back sequence index, digit-span/stroop trial index) so the
+ // server can recompute the answer key. Absent for math/memory drills.
+ index: z.number().int().min(0).optional(),
expected: z.union([z.number(), z.string()]).optional(),
answered: z.union([z.number(), z.string()]).nullable(),
correct: z.boolean().optional(),
@@ -41,7 +46,9 @@ const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', '
const MEMORY_DRILL_TYPES = ['memory-fill-blank', 'memory-sequence', 'memory-element-flash'];
// Memory drills supported by the POST runner (client-side scoring with string comparison)
const POST_SUPPORTED_MEMORY_TYPES = ['memory-sequence', 'memory-element-flash'];
-const DRILL_TYPES = [...MATH_DRILL_TYPES, ...LLM_DRILL_TYPES, ...MEMORY_DRILL_TYPES];
+// Cognitive drills (deterministic, no LLM) — n-back / digit-span / stroop.
+// Sourced from meatspacePostCognitive.js so the type list has one owner.
+const DRILL_TYPES = [...MATH_DRILL_TYPES, ...LLM_DRILL_TYPES, ...MEMORY_DRILL_TYPES, ...COGNITIVE_DRILL_TYPES];
const drillTypeConfigSchema = z.object({
enabled: z.boolean().optional(),
@@ -54,7 +61,15 @@ const drillTypeConfigSchema = z.object({
maxDigits: z.number().int().min(1).max(4).optional(),
bases: z.array(z.number().int().min(2).max(20)).min(1).optional(),
maxExponent: z.number().int().min(2).max(20).optional(),
- tolerancePct: z.number().min(1).max(50).optional()
+ tolerancePct: z.number().min(1).max(50).optional(),
+ // --- Cognitive drill knobs (n-back / digit-span / stroop) ---
+ n: z.number().int().min(1).max(3).optional(),
+ length: z.number().int().min(6).max(60).optional(),
+ stimulusMs: z.number().int().min(500).max(5000).optional(),
+ 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()
});
// Task result within a session
@@ -107,6 +122,11 @@ export const postConfigUpdateSchema = z.object({
model: z.string().nullable().optional(),
drillTypes: z.record(z.enum(LLM_DRILL_TYPES), llmDrillTypeConfigSchema).optional()
}).optional(),
+ // Deterministic cognitive drills — no provider, so no provider/model fields.
+ cognitive: z.object({
+ enabled: z.boolean().optional(),
+ drillTypes: z.record(z.enum(COGNITIVE_DRILL_TYPES), drillTypeConfigSchema).optional()
+ }).optional(),
sessionModules: z.array(z.string()).optional(),
scoring: z.object({
weights: z.record(z.number().min(0).max(1)).optional()
@@ -215,4 +235,4 @@ export const trainingEntrySchema = z.object({
totalMs: z.number().min(0),
});
-export { LLM_DRILL_TYPES, MATH_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES };
+export { LLM_DRILL_TYPES, MATH_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES, COGNITIVE_DRILL_TYPES };
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index 001a63322d..c218144793 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -11,6 +11,7 @@ import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js
import { deepMerge, isPlainObject } from '../lib/objects.js';
import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES } from '../lib/postValidation.js';
import { adaptDrillConfig, ADAPTIVE_SPECS, ADAPTIVE_DEFAULTS } from '../lib/postAdaptive.js';
+import { COGNITIVE_DRILL_TYPES, generateCognitiveDrill, scoreCognitiveDrill } from './meatspacePostCognitive.js';
const MEATSPACE_DIR = PATHS.meatspace;
const SESSIONS_FILE = join(MEATSPACE_DIR, 'post-sessions.json');
@@ -39,8 +40,18 @@ const DEFAULT_CONFIG = {
'pun-wordplay': { enabled: true, count: 5, timeLimitSec: 120 }
}
},
+ // Deterministic cognitive drills (working-memory / attention / inhibition).
+ // No provider calls — enabled by default since they're free to run.
+ cognitive: {
+ enabled: true,
+ 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 }
+ }
+ },
sessionModules: ['mental-math'],
- scoring: { weights: { 'mental-math': 1.0, 'llm-drills': 1.0 } },
+ scoring: { weights: { 'mental-math': 1.0, 'llm-drills': 1.0, 'cognitive': 1.0 } },
// Opt-in adaptive difficulty (default OFF). When enabled, math drills are
// nudged harder/easier at generation time from recent scored performance.
adaptive: { enabled: false }
@@ -124,6 +135,13 @@ export async function submitPostSession(sessionData) {
return { ...rest, score: 0 };
}
+ // Cognitive drills: deterministic — recompute the answer key from the
+ // generated drillData (never trust client `correct`/`score`).
+ if (COGNITIVE_DRILL_TYPES.includes(rest.type)) {
+ const { score, questions } = scoreCognitiveDrill(rest.type, rest.drillData, rest.questions || []);
+ return { ...rest, questions, score };
+ }
+
// Math drills: strip correct from individual questions and rescore
const sanitizedQuestions = (rest.questions || []).map(q => {
const { correct: _qCorrect, ...qRest } = q;
@@ -346,6 +364,10 @@ export function generateDrill(type, config = {}) {
return generatePowers(config.bases, config.maxExponent, config.count);
case 'estimation':
return generateEstimation(config.count, config.tolerancePct);
+ case 'n-back':
+ case 'digit-span':
+ case 'stroop':
+ return generateCognitiveDrill(type, config);
default:
return null;
}
diff --git a/server/services/meatspacePostCognitive.js b/server/services/meatspacePostCognitive.js
new file mode 100644
index 0000000000..c14ae9ed06
--- /dev/null
+++ b/server/services/meatspacePostCognitive.js
@@ -0,0 +1,252 @@
+/**
+ * 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
+ *
+ * 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
+ * `correct`/`score` is never trusted (mirrors the math `scoreDrill` contract).
+ * NO AI-provider calls happen anywhere in this module.
+ */
+
+// 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'];
+
+const NBACK_LETTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
+
+// Named colors used by the Stroop drill. `hex` is the rendered ink color and
+// the swatch on the answer buttons; `name` is the correct answer token.
+export const STROOP_COLORS = [
+ { name: 'red', hex: '#ef4444' },
+ { name: 'blue', hex: '#3b82f6' },
+ { name: 'green', hex: '#22c55e' },
+ { name: 'yellow', hex: '#eab308' },
+];
+
+// =============================================================================
+// HELPERS
+// =============================================================================
+
+function clampInt(value, min, max, fallback) {
+ const n = Math.round(Number(value));
+ if (!Number.isFinite(n)) return fallback;
+ return Math.min(max, Math.max(min, n));
+}
+
+function pick(arr) {
+ return arr[Math.floor(Math.random() * arr.length)];
+}
+
+function clampMs(ms, refMs) {
+ return Math.min(Math.max(Number(ms) || 0, 0), refMs);
+}
+
+/**
+ * Shared 0-100 score: 80% accuracy + 20% speed. `refMs` is the per-trial
+ * response window used for the speed bonus (avg RT over answered trials).
+ */
+function accuracySpeedScore(recomputed, refMs) {
+ if (!recomputed.length) return 0;
+ const correctRatio = recomputed.filter(q => q.correct).length / recomputed.length;
+ const timed = recomputed.filter(q => q.answered != null && q.responseMs > 0);
+ const avgMs = timed.length ? timed.reduce((s, q) => s + q.responseMs, 0) / timed.length : refMs;
+ const speedBonus = refMs > 0 ? Math.max(0, 1 - avgMs / refMs) : 0;
+ return Math.min(100, Math.max(0, Math.round((correctRatio * 0.8 + speedBonus * 0.2) * 100)));
+}
+
+// =============================================================================
+// GENERATORS
+// =============================================================================
+
+/**
+ * N-back sequence. ~30% of decision positions (index >= n) are targets — the
+ * current letter equals the one N steps back. `targets` is a convenience mirror
+ * for the client; scoring recomputes it from `sequence` + `config.n`.
+ */
+export function generateNBack(config = {}) {
+ const n = clampInt(config.n, 1, 3, 2);
+ const length = clampInt(config.length, n + 5, 60, 20);
+ const sequence = [];
+ const targets = [];
+ for (let i = 0; i < length; i++) {
+ if (i < n) {
+ sequence.push(pick(NBACK_LETTERS));
+ targets.push(false);
+ } else if (Math.random() < 0.3) {
+ sequence.push(sequence[i - n]);
+ targets.push(true);
+ } else {
+ const nBackItem = sequence[i - n];
+ let letter = pick(NBACK_LETTERS);
+ if (letter === nBackItem) letter = pick(NBACK_LETTERS.filter(l => l !== nBackItem));
+ sequence.push(letter);
+ targets.push(false);
+ }
+ }
+ return {
+ type: 'n-back',
+ config: { n, length, stimulusMs: clampInt(config.stimulusMs, 1000, 5000, 2500) },
+ sequence,
+ targets,
+ };
+}
+
+/**
+ * Digit-span trials of increasing length, from startLength to maxLength. The
+ * expected recall is the sequence forward, or reversed for the backward variant.
+ */
+export function generateDigitSpan(config = {}) {
+ const direction = config.direction === 'backward' ? 'backward' : 'forward';
+ const startLength = clampInt(config.startLength, 3, 9, 3);
+ const maxLength = clampInt(config.maxLength, startLength, 12, 8);
+ const sequences = [];
+ for (let len = startLength; len <= maxLength; len++) {
+ const digits = [];
+ for (let i = 0; i < len; i++) digits.push(Math.floor(Math.random() * 10));
+ sequences.push({ digits, length: len });
+ }
+ return {
+ type: 'digit-span',
+ config: { direction, startLength, maxLength, showMs: clampInt(config.showMs, 400, 4000, 1000) },
+ sequences,
+ };
+}
+
+/**
+ * Stroop trials. ~25% congruent (word matches ink), the rest incongruent. The
+ * correct answer is always the INK color.
+ */
+export function generateStroop(config = {}) {
+ const count = clampInt(config.count, 5, 40, 15);
+ const trials = [];
+ for (let i = 0; i < count; i++) {
+ const wordColor = pick(STROOP_COLORS);
+ const inkColor = Math.random() < 0.25
+ ? wordColor
+ : pick(STROOP_COLORS.filter(c => c.name !== wordColor.name));
+ trials.push({
+ word: wordColor.name,
+ inkColor: inkColor.name,
+ inkHex: inkColor.hex,
+ congruent: wordColor.name === inkColor.name,
+ });
+ }
+ return {
+ type: 'stroop',
+ config: { count },
+ trials,
+ options: STROOP_COLORS.map(c => ({ name: c.name, hex: c.hex })),
+ };
+}
+
+export function generateCognitiveDrill(type, config = {}) {
+ switch (type) {
+ case 'n-back':
+ return generateNBack(config);
+ case 'digit-span':
+ return generateDigitSpan(config);
+ case 'stroop':
+ return generateStroop(config);
+ default:
+ return null;
+ }
+}
+
+// =============================================================================
+// SCORERS (recompute the answer key from drillData — never trust client marks)
+// =============================================================================
+
+function scoreNBack(drillData, questions) {
+ const sequence = drillData?.sequence || [];
+ const n = drillData?.config?.n ?? 2;
+ const refMs = drillData?.config?.stimulusMs || 2500;
+ const recomputed = questions.map(q => {
+ const i = Number.isInteger(q.index) ? q.index : -1;
+ const isTarget = i >= n && sequence[i] != null && sequence[i] === sequence[i - n];
+ const expected = isTarget ? 'match' : 'no-match';
+ // Anything but an explicit "match" counts as "no-match" (including a skip).
+ const answered = q.answered === 'match' ? 'match' : q.answered == null ? null : 'no-match';
+ const effective = answered === 'match' ? 'match' : 'no-match';
+ return {
+ prompt: q.prompt ?? (i >= 0 ? sequence[i] : ''),
+ index: i,
+ expected,
+ answered,
+ correct: effective === expected,
+ responseMs: clampMs(q.responseMs, refMs),
+ };
+ });
+ return { score: accuracySpeedScore(recomputed, refMs), questions: recomputed };
+}
+
+function scoreDigitSpan(drillData, questions) {
+ const sequences = drillData?.sequences || [];
+ const direction = drillData?.config?.direction === 'backward' ? 'backward' : 'forward';
+ const maxLength = drillData?.config?.maxLength || 12;
+ const recomputed = questions.map(q => {
+ const seq = sequences[q.index] || {};
+ const digits = Array.isArray(seq.digits) ? seq.digits : [];
+ const ordered = direction === 'backward' ? [...digits].reverse() : digits;
+ const expected = ordered.join('');
+ const answered = q.answered == null ? null : String(q.answered).replace(/\D/g, '');
+ const correct = expected.length > 0 && answered === expected;
+ return {
+ prompt: q.prompt ?? `${digits.length}-digit (${direction})`,
+ index: q.index,
+ expected,
+ answered,
+ correct,
+ length: digits.length,
+ responseMs: clampMs(q.responseMs, (digits.length || 1) * 2000),
+ };
+ });
+ // Span-weighted: accuracy + reaching longer spans. Speed is not part of a
+ // recall span, so this scorer intentionally omits the RT bonus.
+ const correctRatio = recomputed.length ? recomputed.filter(q => q.correct).length / recomputed.length : 0;
+ const span = recomputed.filter(q => q.correct).reduce((m, q) => Math.max(m, q.length || 0), 0);
+ const spanBonus = maxLength > 0 ? Math.min(1, span / maxLength) : 0;
+ const score = Math.min(100, Math.max(0, Math.round((correctRatio * 0.7 + spanBonus * 0.3) * 100)));
+ return { score, questions: recomputed, span };
+}
+
+function scoreStroop(drillData, questions) {
+ const trials = drillData?.trials || [];
+ const refMs = 1500;
+ const recomputed = questions.map(q => {
+ const trial = trials[q.index] || {};
+ const expected = trial.inkColor || '';
+ const answered = q.answered == null ? null : String(q.answered).toLowerCase().trim();
+ return {
+ prompt: q.prompt ?? trial.word ?? '',
+ index: q.index,
+ expected,
+ answered,
+ correct: expected !== '' && answered === expected,
+ responseMs: clampMs(q.responseMs, refMs),
+ };
+ });
+ 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? }`.
+ */
+export function scoreCognitiveDrill(type, drillData, questions = []) {
+ const list = Array.isArray(questions) ? questions : [];
+ switch (type) {
+ case 'n-back':
+ return scoreNBack(drillData, list);
+ case 'digit-span':
+ return scoreDigitSpan(drillData, list);
+ case 'stroop':
+ return scoreStroop(drillData, list);
+ default:
+ return { score: 0, questions: list };
+ }
+}
diff --git a/server/services/meatspacePostCognitive.test.js b/server/services/meatspacePostCognitive.test.js
new file mode 100644
index 0000000000..e7fce2e08a
--- /dev/null
+++ b/server/services/meatspacePostCognitive.test.js
@@ -0,0 +1,137 @@
+import { describe, it, expect } from 'vitest';
+import {
+ COGNITIVE_DRILL_TYPES,
+ STROOP_COLORS,
+ generateNBack,
+ generateDigitSpan,
+ generateStroop,
+ generateCognitiveDrill,
+ scoreCognitiveDrill,
+} from './meatspacePostCognitive.js';
+
+describe('cognitive drill generators', () => {
+ it('n-back respects n/length clamps and never places a target in the lead-in', () => {
+ const drill = generateNBack({ n: 2, length: 24 });
+ expect(drill.type).toBe('n-back');
+ expect(drill.config.n).toBe(2);
+ expect(drill.sequence).toHaveLength(24);
+ expect(drill.targets.slice(0, 2)).toEqual([false, false]);
+ // targets mirror the actual n-back relationship
+ drill.sequence.forEach((letter, i) => {
+ if (i < 2) return;
+ const isMatch = letter === drill.sequence[i - 2];
+ expect(drill.targets[i]).toBe(isMatch);
+ });
+ });
+
+ it('n-back clamps out-of-range n and length', () => {
+ const drill = generateNBack({ n: 9, length: 1 });
+ expect(drill.config.n).toBeLessThanOrEqual(3);
+ expect(drill.config.n).toBeGreaterThanOrEqual(1);
+ expect(drill.sequence.length).toBeGreaterThanOrEqual(drill.config.n + 5);
+ });
+
+ it('digit-span builds one sequence per length from start to max', () => {
+ const drill = generateDigitSpan({ direction: 'backward', startLength: 3, maxLength: 6 });
+ expect(drill.type).toBe('digit-span');
+ expect(drill.config.direction).toBe('backward');
+ expect(drill.sequences.map(s => s.length)).toEqual([3, 4, 5, 6]);
+ for (const s of drill.sequences) {
+ expect(s.digits).toHaveLength(s.length);
+ for (const d of s.digits) expect(d).toBeGreaterThanOrEqual(0), expect(d).toBeLessThanOrEqual(9);
+ }
+ });
+
+ it('stroop produces the requested trial count with a valid ink answer', () => {
+ const drill = generateStroop({ count: 12 });
+ expect(drill.type).toBe('stroop');
+ expect(drill.trials).toHaveLength(12);
+ const names = STROOP_COLORS.map(c => c.name);
+ for (const t of drill.trials) {
+ expect(names).toContain(t.word);
+ expect(names).toContain(t.inkColor);
+ expect(t.congruent).toBe(t.word === t.inkColor);
+ }
+ expect(drill.options.map(o => o.name).sort()).toEqual([...names].sort());
+ });
+
+ it('generateCognitiveDrill dispatches by type and returns null for unknown', () => {
+ expect(generateCognitiveDrill('n-back').type).toBe('n-back');
+ expect(generateCognitiveDrill('digit-span').type).toBe('digit-span');
+ expect(generateCognitiveDrill('stroop').type).toBe('stroop');
+ expect(generateCognitiveDrill('nope')).toBeNull();
+ });
+
+ it('exposes exactly the three shipped cognitive types', () => {
+ expect(COGNITIVE_DRILL_TYPES).toEqual(['n-back', 'digit-span', 'stroop']);
+ });
+});
+
+describe('cognitive drill scorers (recompute the answer key, never trust client)', () => {
+ it('n-back scores a perfect run near the top and rewards no wrong presses', () => {
+ // Deterministic sequence: A B A B A → with n=2, positions 2,3,4 are all targets.
+ const drillData = { type: 'n-back', config: { n: 2, stimulusMs: 2000 }, sequence: ['A', 'B', 'A', 'B', 'A'] };
+ const questions = [
+ { index: 2, answered: 'match', responseMs: 400 },
+ { index: 3, answered: 'match', responseMs: 400 },
+ { index: 4, answered: 'match', responseMs: 400 },
+ ];
+ const { score, questions: scored } = scoreCognitiveDrill('n-back', drillData, questions);
+ expect(scored.every(q => q.correct)).toBe(true);
+ // Score is the shared 80% accuracy + 20% speed blend: perfect accuracy floors
+ // it at 80, and a 400ms avg response against the 2000ms stimulus window adds
+ // 0.2 × (1 − 400/2000) × 100 = 16 → 96. (100 is only reached at instantaneous
+ // response, so it's an aspirational ceiling, like a golf score.)
+ expect(score).toBe(96);
+ });
+
+ it('n-back marks a false-positive press wrong even if client claims correct', () => {
+ const drillData = { type: 'n-back', config: { n: 2 }, sequence: ['A', 'B', 'C', 'D'] };
+ // index 2 (C) is NOT a match of index 0 (A); pressing "match" is wrong.
+ const { score, questions } = scoreCognitiveDrill('n-back', drillData, [
+ { index: 2, answered: 'match', correct: true, responseMs: 300 },
+ { index: 3, answered: null, responseMs: 0 },
+ ]);
+ expect(questions[0].correct).toBe(false); // client's correct:true ignored
+ expect(questions[1].correct).toBe(true); // correctly withheld
+ expect(score).toBeLessThan(100);
+ });
+
+ it('digit-span expects the reversed sequence for the backward variant', () => {
+ const drillData = {
+ type: 'digit-span',
+ config: { direction: 'backward', maxLength: 4 },
+ sequences: [{ digits: [1, 2, 3], length: 3 }, { digits: [4, 5, 6, 7], length: 4 }],
+ };
+ const { questions } = scoreCognitiveDrill('digit-span', drillData, [
+ { index: 0, answered: '321', responseMs: 2000 }, // correct reverse
+ { index: 1, answered: '4567', responseMs: 2000 }, // forward → wrong for backward
+ ]);
+ expect(questions[0].correct).toBe(true);
+ expect(questions[0].expected).toBe('321');
+ expect(questions[1].correct).toBe(false);
+ expect(questions[1].expected).toBe('7654');
+ });
+
+ it('stroop grades against the ink color, not the word', () => {
+ const drillData = {
+ type: 'stroop',
+ trials: [
+ { word: 'red', inkColor: 'blue', inkHex: '#3b82f6' },
+ { word: 'green', inkColor: 'green', inkHex: '#22c55e' },
+ ],
+ };
+ const { questions } = scoreCognitiveDrill('stroop', drillData, [
+ { index: 0, answered: 'blue', responseMs: 500 }, // ink=blue → correct
+ { index: 1, answered: 'green', responseMs: 500 },
+ ]);
+ expect(questions[0].correct).toBe(true);
+ expect(questions[1].correct).toBe(true);
+ });
+
+ it('unknown type yields a zero score and passes questions through', () => {
+ const result = scoreCognitiveDrill('mystery', {}, [{ index: 0 }]);
+ expect(result.score).toBe(0);
+ expect(result.questions).toHaveLength(1);
+ });
+});