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
Merge remote-tracking branch 'origin/main' into next/issue-2006
Adam Eivy101d6bae98d3
diff --cc .changelog/NEXT.mdindex 6db21e64b2,5aa90f2baf..b340c38e53--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@@ -28,10 -28,11 +28,12 @@@- **[issue-1991] POST memory items now resurface on a spaced-repetition schedule.** Memory items (songs, poems, speeches, sequences) tracked mastery but had no review cadence — practice was entirely user-initiated, with nothing telling you *what to review today*. Each item now carries a lightweight SM-2-inspired schedule (ease, interval, next-review date): finishing a practice session reschedules the item automatically — a strong, mostly-correct session pushes the next review further out, while a miss-heavy session resets it to "due now" so it comes back around immediately. The Memory Builder gains a **Due Today (N)** banner listing what's ready for review with a one-click **Review Next**, plus a small "Due" badge on each item that's ready; the count updates the moment you finish practicing. Existing items keep working unchanged — a migration stamps every pre-existing item with a "due now" default so nothing gets stranded — and a new `GET /post/memory-items/due` endpoint lists due items most-overdue first.- **[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)+ - **[issue-1997] Morse Trainer now logs practice to your POST training streak, plus a new Head Copy mode.** Completing a Copy or Send round previously only updated the trainer's own `localStorage` prefs (Koch level, best round) — it never touched POST's training log, so Morse practice was invisible to the rest of the app. Every completed round/check now logs to the same training log other POST training-mode drills use, and the Settings panel shows your training streak plus Morse-specific sessions-logged/accuracy right next to the existing Koch-level readout. Also ships a new **Head Copy** mode alongside Copy and Send: identical Koch-progression practice, but with the on-screen morse-code hints and reference cheat sheet hidden, so you're copying purely from memory. Deep-linkable at `/post/morse/head-copy` and reachable from ⌘K/voice nav like the existing modes. Existing Copy/Send behavior and prefs are unchanged. (`client/src/components/meatspace/post/MorseTrainer.jsx`, `server/lib/postValidation.js`, `server/lib/navManifest.js`, Closes #1997)- **[issue-1994] Optional daily reminder for your POST session.** POST is meant to be a daily habit, but nothing ever nudged you to actually do it. A new **Daily Reminder** toggle in the Drill Configuration screen — off by default — lets you pick a time of day; if you haven't completed a session by then, you'll get a single in-app notification reminding you, and it stays silent once you've already practiced that day. Turning it off stops all nudges immediately. No AI calls are involved, and changing the time takes effect right away without a restart. (Closes #1994)- **[issue-2008] Cognitive drills (N-Back, Digit Span, Stroop) no longer show a "Time Limit" field that did nothing.** These three drills are self-paced/stimulus-driven and never counted down against it, unlike Mental Math and Wit & Memory drills, which genuinely do enforce their time limit. The dead field is removed from the Drill Configuration screen and drill summaries, along with the unreachable `stimulusMs`/`showMs` config pass-through (no UI ever set them — the drills always used their built-in pacing anyway). No behavior change to how the drills actually play. (Closes #2008)+ - **[issue-2009] Hardened the N-Back / Digit Span / Stroop cognitive drills against silent scoring regressions.** The result-assembly logic that turns your answers into the `questions[]` payload the server rescores from (N-Back's off-by-one-prone target lookup, Digit Span's forward-vs-backward comparison, Stroop's ink-vs-word grading) is now covered by focused unit tests, matching the test coverage the other POST drill runners already had. No behavior change. (`client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx`, Closes #2009)- **[issue-2010] Memory drills inside a POST session now count as a review.** Practicing a memory item (Sequence or Element Flash) as part of a scored POST session previously updated your score but never touched that item's spaced-repetition schedule — so it stayed on "Due Today" even right after you'd just reviewed it, which only the dedicated Memory Builder practice screen would clear. A POST-session memory drill now advances the item's schedule the same way MemoryBuilder practice does (a strong session pushes the next review out; a miss-heavy one resets it to due-now), so "Due Today" and the review streak stay accurate no matter which screen you practiced from. (`server/services/meatspacePost.js`, `server/services/meatspacePostMemory.js`, `client/src/hooks/usePostSession.js`, Closes #2010)+- **[issue-2006] Three more Cognitive drills — Schulte Table, Mental Rotation, and Reaction Time.** Rounds out the Cognitive domain from #1993 with the three follow-up exercises: **Schulte Table** (scan a shuffled numbered grid and tap 1, 2, 3... in order — visual attention and scan speed), **Mental Rotation** (pick which of four shapes is the reference shape rotated, not mirrored — spatial reasoning), and **Reaction Time** (simple or choice reaction-time baseline, with a false-start penalty for jumping the gun). All three are configurable, playable in Test and Train modes, scored, and saved to your training history alongside the rest of POST — with zero AI provider calls, same as the rest of the Cognitive domain.## Media Generationdiff --cc client/src/components/meatspace/post/PostCognitiveDrillRunner.jsxindex 4bc29bf4a5,bdc33065c6..38d9c8a9f3--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx@@@ -60,26 -54,84 +60,118 @@@ export function localAccuracyScore(quesreturn 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>+ );+}++ // Shared result-assembly shape every sub-runner hands to `onComplete`. The+ // server rescores deterministically from `drillData`/`questions` on save+ // (server/services/meatspacePostCognitive.js) — this is the client-side+ // mirror, and its `index`/`answered`/`responseMs` fields are what that+ // rescoring depends on.+ export function buildCognitiveResult({ type, drill, questions, totalMs }) {+ return {+ module: 'cognitive',+ type,+ config: drill.config,+ drillData: drill,+ questions,+ score: localAccuracyScore(questions),+ totalMs,+ };+ }++ // N-BACK — pure result assembly: given the full letter sequence, the lag `n`,+ // and the parallel `answers` array (index-aligned with `seq`, each entry+ // `{ answered: 'match'|null, responseMs }`), build the scored `questions[]`.+ // Only positions `i >= n` have a defined target (there's no "n back" before+ // that), so the first `n` letters are excluded — the off-by-one this guards+ // against is including/excluding the boundary position `i === n` itself.+ export function buildNBackQuestions(seq, n, answers) {+ return seq+ .map((letter, i) => ({ letter, i }))+ .filter(({ i }) => i >= n)+ .map(({ letter, i }) => {+ const a = answers[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,+ };+ });+ }++ // DIGIT SPAN — pure scoring for one recalled sequence. `direction` decides+ // whether the expected answer is the digits in shown order ('forward') or+ // reversed ('backward') — the bug this guards against is comparing the+ // typed answer against the wrong ordering. Returns both the persisted+ // `question` (what `finish()` assembles into the result) and the raw+ // `expected`/`answeredRaw` strings the training-mode feedback UI displays.+ export function scoreDigitSpanRecall({ digits, direction, index, answeredStr, responseMs }) {+ const ordered = direction === 'backward' ? [...digits].reverse() : digits;+ const expected = ordered.join('');+ const answeredRaw = (answeredStr || '').replace(/\D/g, '');+ return {+ question: {+ prompt: `${digits.length}-digit (${direction})`,+ index,+ answered: answeredRaw.length ? answeredRaw : null,+ correct: answeredRaw.length > 0 && answeredRaw === expected,+ responseMs,+ length: digits.length,+ },+ expected,+ answeredRaw,+ };+ }++ // STROOP — pure scoring for one trial: correct iff the picked color name+ // matches the word's INK color (`trial.inkColor`), not the word text itself+ // — the bug this guards against is accidentally grading against the word.+ export function scoreStroopTrial({ trial, index, colorName, responseMs }) {+ return {+ prompt: trial.word,+ index,+ answered: colorName,+ correct: colorName === trial.inkColor,+ responseMs,+ };+ }+++// MENTAL ROTATION — pure scoring for one trial: correct iff the picked option++// index is the option that's the SAME shape (just rotated), not a mirror or++// distractor. Mirrors `scoreStroopTrial`'s shape so both trial-based drills++// share one testable pattern.++export function scoreMentalRotationTrial({ trial, index, optionIndex, responseMs }) {++ return {++ prompt: `shape ${trial.shape || ''}`,++ index,++ answered: optionIndex,++ correct: optionIndex === trial.correctIndex,++ responseMs,++ };++}++// =============================================================================// N-BACK — a letter stream; signal when the current letter matches N steps back// =============================================================================@@@ -522,456 -527,3 +567,431 @@@ function StroopRunner({ drill, drillInd</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);+ // Mirrors `target` synchronously so a double-tap/double-click that fires two+ // handleClick calls before React commits the setTarget update can't both read+ // the same stale `target` and both advance — the second call sees the bumped+ // ref and is treated as a miss instead of a duplicate correct answer.+ const targetRef = useRef(target);++ useEffect(() => () => clearTimeout(flashTimeoutRef.current), []);++ const finish = useCallback(() => {- onComplete({- module: 'cognitive',++ onComplete(buildCognitiveResult({+ type: 'schulte-table',- config: drill.config,- drillData: drill,++ 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) => {+ const current = targetRef.current;+ if (value !== current) {+ setFlash(value);+ clearTimeout(flashTimeoutRef.current);+ flashTimeoutRef.current = setTimeout(() => setFlash(null), 200);+ return;+ }+ // Advance the ref immediately (synchronously) so a second handleClick call+ // racing in before this render commits sees the bumped value, not `current`.+ targetRef.current = current + 1;+ questionsRef.current.push({+ prompt: `${current}`,+ index: current - 1,+ answered: current,+ correct: true,+ responseMs: Date.now() - stepStartRef.current,+ });+ stepStartRef.current = Date.now();+ if (current >= total) finishRef.current();+ else setTarget(current + 1);+ }, [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,- });++ onComplete(buildCognitiveResult({ type: 'mental-rotation', drill, 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 question = scoreMentalRotationTrial({ trial, index: trialIdx, optionIndex, responseMs: Date.now() - trialStartRef.current });++ answersRef.current[trialIdx] = question;+ const isLast = trialIdx + 1 >= trials.length;+ if (isTraining) {- setFeedback({ correct, expected: trial.correctIndex, isLast });++ setFeedback({ correct: question.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);+ // Separate refs: the "reveal the stimulus" timer (armed per trial) and the+ // "advance to the next trial" timer (armed on response) must never share one+ // ref — overwriting a shared ref on response leaves the reveal timer's+ // callback un-cancelled, so a false start can leak a stale setPhase('go')+ // into a later trial once the ref no longer points at it.+ const armTimeoutRef = useRef(null);+ const advanceTimeoutRef = useRef(null);+ const advancingRef = useRef(false);++ useEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ clearTimeout(armTimeoutRef.current);+ clearTimeout(advanceTimeoutRef.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,- });++ onComplete(buildCognitiveResult({ type: 'reaction-time', drill, 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. Capture the timer in a local+ // variable so this effect's cleanup always cancels ITS OWN timer, even if+ // `armTimeoutRef.current` was reassigned in the meantime.+ useEffect(() => {+ if (trialIdx >= trials.length) { finishRef.current(); return; }+ advancingRef.current = false;+ stimulusShownRef.current = false;+ setPhase('waiting');+ setLastResult(null);+ const delay = trials[trialIdx]?.delayMs || 1000;+ const revealTimer = setTimeout(() => {+ if (!mountedRef.current) return;+ stimulusShownRef.current = true;+ goStartRef.current = Date.now();+ setPhase('go');+ }, delay);+ armTimeoutRef.current = revealTimer;+ return () => clearTimeout(revealTimer);+ }, [trialIdx]);++ const recordAndAdvance = useCallback((result) => {+ if (advancingRef.current) return;+ advancingRef.current = true;+ // A false start fires this before the reveal timer elapses — cancel it so+ // it can't flip `phase`/`stimulusShownRef` on a later trial.+ clearTimeout(armTimeoutRef.current);+ answersRef.current[trialIdx] = {+ prompt: mode === 'choice' ? `target ${trials[trialIdx]?.target ?? ''}` : 'react',+ index: trialIdx,+ ...result,+ };+ setLastResult(result);+ setPhase('result');+ const isLast = trialIdx + 1 >= trials.length;+ advanceTimeoutRef.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 --cc client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsxindex c65d73a1bc,adc08e2fac..c2a62f2005--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx@@@ -1,134 -1,202 +1,355 @@@-import { describe, it, expect } from 'vitest';-import {+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { render, screen, fireEvent, act } from '@testing-library/react';- import PostCognitiveDrillRunner from './PostCognitiveDrillRunner';++import PostCognitiveDrillRunner, {+ localAccuracyScore,+ buildCognitiveResult,+ buildNBackQuestions,+ scoreDigitSpanRecall,+ scoreStroopTrial,++ scoreMentalRotationTrial,+ } from './PostCognitiveDrillRunner';++ // Result-assembly tests for PostCognitiveDrillRunner's `finish()` builders.+ // The server rescores each drill deterministically from `drillData`/`questions`+ // (server/services/meatspacePostCognitive.js), so the `index`/`answered`/+ // `responseMs` shape these functions produce is load-bearing — a regression+ // here (n-back off-by-one, digit-span reversed-answer comparison, stroop+ // ink-vs-word grading) would pass silently in the interactive UI.++ describe('localAccuracyScore', () => {+ it('returns 0 for an empty question list', () => {+ expect(localAccuracyScore([])).toBe(0);+ });++ it('rounds the percentage of correct answers', () => {+ expect(localAccuracyScore([{ correct: true }, { correct: true }, { correct: false }])).toBe(67);+ });++ it('returns 100 when every question is correct', () => {+ expect(localAccuracyScore([{ correct: true }, { correct: true }])).toBe(100);+ });+ });++ describe('buildCognitiveResult', () => {+ it('assembles the full onComplete payload shape', () => {+ const drill = { type: 'n-back', config: { n: 2 }, sequence: ['A', 'B'] };+ const questions = [{ correct: true }, { correct: false }];+ const result = buildCognitiveResult({ type: 'n-back', drill, questions, totalMs: 4200 });+ expect(result).toEqual({+ module: 'cognitive',+ type: 'n-back',+ config: { n: 2 },+ drillData: drill,+ questions,+ score: 50,+ totalMs: 4200,+ });+ });+ });++ describe('buildNBackQuestions', () => {+ const seq = ['A', 'B', 'A', 'C', 'B'];+ const n = 2;++ it('excludes the first n letters — no target is defined before position n', () => {+ const answers = seq.map(() => ({ answered: null, responseMs: 0 }));+ const questions = buildNBackQuestions(seq, n, answers);+ expect(questions).toHaveLength(seq.length - n);+ expect(questions.map(q => q.index)).toEqual([2, 3, 4]);+ });++ it('includes the boundary position i === n (off-by-one guard)', () => {+ const answers = seq.map(() => ({ answered: null, responseMs: 0 }));+ const questions = buildNBackQuestions(seq, n, answers);+ // Position n=2 (seq[2]='A') IS a valid decision point (compares against seq[0]='A').+ expect(questions[0].index).toBe(2);+ expect(questions[0].prompt).toBe('A');+ });++ it('marks a true target correctly answered "match" as correct', () => {+ // i=2: seq[2]='A' === seq[0]='A' -> isTarget=true. Answered 'match' -> correct.+ const answers = seq.map(() => ({ answered: null, responseMs: 0 }));+ answers[2] = { answered: 'match', responseMs: 300 };+ const questions = buildNBackQuestions(seq, n, answers);+ const q = questions.find(q => q.index === 2);+ expect(q.correct).toBe(true);+ expect(q.answered).toBe('match');+ expect(q.responseMs).toBe(300);+ });++ it('marks a true target left unanswered as incorrect', () => {+ // i=2 is a target; no press recorded.+ const answers = seq.map(() => ({ answered: null, responseMs: 0 }));+ const questions = buildNBackQuestions(seq, n, answers);+ const q = questions.find(q => q.index === 2);+ expect(q.correct).toBe(false);+ expect(q.answered).toBeNull();+ });++ it('marks a false-alarm press (non-target answered "match") as incorrect', () => {+ // i=3: seq[3]='C' !== seq[1]='B' -> isTarget=false. Pressed match anyway -> incorrect.+ const answers = seq.map(() => ({ answered: null, responseMs: 0 }));+ answers[3] = { answered: 'match', responseMs: 250 };+ const questions = buildNBackQuestions(seq, n, answers);+ const q = questions.find(q => q.index === 3);+ expect(q.correct).toBe(false);+ });++ it('marks a correct rejection (non-target left unanswered) as correct', () => {+ // i=4: seq[4]='B' === seq[2]='A'? no -> isTarget=false. No press -> correct rejection.+ const answers = seq.map(() => ({ answered: null, responseMs: 0 }));+ const questions = buildNBackQuestions(seq, n, answers);+ const q = questions.find(q => q.index === 4);+ expect(q.correct).toBe(true);+ });+ });++ describe('scoreDigitSpanRecall', () => {+ it('scores a forward recall correct when digits match in shown order', () => {+ const { question, expected } = scoreDigitSpanRecall({+ digits: [1, 2, 3],+ direction: 'forward',+ index: 0,+ answeredStr: '123',+ responseMs: 1500,+ });+ expect(expected).toBe('123');+ expect(question).toEqual({+ prompt: '3-digit (forward)',+ index: 0,+ answered: '123',+ correct: true,+ responseMs: 1500,+ length: 3,+ });+ });++ it('scores a backward recall correct only when digits are reversed', () => {+ const { question, expected } = scoreDigitSpanRecall({+ digits: [1, 2, 3],+ direction: 'backward',+ index: 0,+ answeredStr: '321',+ responseMs: 900,+ });+ expect(expected).toBe('321');+ expect(question.correct).toBe(true);+ });++ it('scores a backward recall submitted in forward order as incorrect', () => {+ // Guards the exact bug class named in the issue: comparing against the+ // wrong ordering for backward digit-span.+ const { question } = scoreDigitSpanRecall({+ digits: [1, 2, 3],+ direction: 'backward',+ index: 0,+ answeredStr: '123',+ responseMs: 900,+ });+ expect(question.correct).toBe(false);+ });++ it('treats an empty answer as unanswered (null), not empty-string-correct', () => {+ const { question } = scoreDigitSpanRecall({+ digits: [4, 5],+ direction: 'forward',+ index: 1,+ answeredStr: '',+ responseMs: 0,+ });+ expect(question.answered).toBeNull();+ expect(question.correct).toBe(false);+ });++ it('strips non-digit characters before comparing', () => {+ const { question } = scoreDigitSpanRecall({+ digits: [7, 8, 9],+ direction: 'forward',+ index: 0,+ answeredStr: '7-8-9',+ responseMs: 500,+ });+ expect(question.answered).toBe('789');+ expect(question.correct).toBe(true);+ });+ });++ describe('scoreStroopTrial', () => {+ it('grades correct when the picked color matches the INK color, not the word', () => {+ // Classic Stroop conflict: word says "RED" but ink is rendered blue.+ const trial = { word: 'RED', inkColor: 'blue' };+ const question = scoreStroopTrial({ trial, index: 0, colorName: 'blue', responseMs: 800 });+ expect(question).toEqual({+ prompt: 'RED',+ index: 0,+ answered: 'blue',+ correct: true,+ responseMs: 800,+ });+ });++ it('grades incorrect when the picked color matches the word text instead of the ink', () => {+ // Guards the exact bug class named in the issue: accidentally grading+ // against the word rather than the ink color.+ const trial = { word: 'RED', inkColor: 'blue' };+ const question = scoreStroopTrial({ trial, index: 0, colorName: 'red', responseMs: 800 });+ expect(question.correct).toBe(false);+ });++ it('grades correct on a congruent trial where word and ink agree', () => {+ const trial = { word: 'GREEN', inkColor: 'green' };+ const question = scoreStroopTrial({ trial, index: 2, colorName: 'green', responseMs: 400 });+ expect(question.correct).toBe(true);+ });+ });++++describe('scoreMentalRotationTrial', () => {++ it('grades correct when the picked option is the rotated (non-mirrored) match', () => {++ const trial = { shape: 'L', correctIndex: 1 };++ const question = scoreMentalRotationTrial({ trial, index: 0, optionIndex: 1, responseMs: 650 });++ expect(question).toEqual({++ prompt: 'shape L',++ index: 0,++ answered: 1,++ correct: true,++ responseMs: 650,++ });++ });++++ it('grades incorrect when the picked option is a distractor/mirror', () => {++ const trial = { shape: 'L', correctIndex: 1 };++ const question = scoreMentalRotationTrial({ trial, index: 0, optionIndex: 0, responseMs: 650 });++ expect(question.correct).toBe(false);++ });++});++// Regression coverage for the reaction-time runner's timer/re-entrancy guards+// (dual armTimeoutRef/advanceTimeoutRef + advancingRef). These are documented+// in-code as deliberate race-condition mitigations but had no test coverage:+// a future edit that collapses the two timer refs back into one, or drops+// the advancingRef guard, would silently reintroduce a stale setPhase('go')+// leak or a double-recorded trial.++function makeSimpleDrill({ count = 1, delayMs = 1000 } = {}) {+ return {+ type: 'reaction-time',+ config: { mode: 'simple', count, minDelayMs: delayMs, maxDelayMs: delayMs, choices: 1 },+ trials: Array.from({ length: count }, () => ({ delayMs })),+ };+}++describe('ReactionTimeRunner race-condition guards', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('cancels the reveal timer on a false start so it cannot leak a stale GO into a later trial', () => {+ const onComplete = vi.fn();+ const drill = makeSimpleDrill({ count: 1, delayMs: 1000 });+ render(+ <PostCognitiveDrillRunner+ drill={drill}+ drillIndex={0}+ drillCount={1}+ onComplete={onComplete}+ isTraining={false}+ />,+ );++ // Respond before the stimulus is revealed — a false start.+ act(() => {+ fireEvent.click(screen.getByRole('button', { name: /wait for the signal/i }));+ });+ expect(screen.getByText('Too soon!')).toBeInTheDocument();++ // The non-training advance delay is 500ms; this is the only trial, so it+ // finishes (calls onComplete) rather than arming a new trial.+ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(onComplete).toHaveBeenCalledTimes(1);+ const result = onComplete.mock.calls[0][0];+ expect(result.questions).toHaveLength(1);+ expect(result.questions[0]).toMatchObject({ falseStart: true, correct: false, answered: null });++ // Advance past the ORIGINAL 1000ms reveal delay. If the reveal timer had+ // not been cancelled on the false start, its stale callback would fire+ // here and flip phase back to 'go' (rendering the GO! button) even+ // though the drill already completed.+ act(() => {+ vi.advanceTimersByTime(1000);+ });+ expect(screen.queryByRole('button', { name: 'GO!' })).not.toBeInTheDocument();+ expect(onComplete).toHaveBeenCalledTimes(1);+ });++ it('does not double-record a response when GO is clicked twice in rapid succession', () => {+ const onComplete = vi.fn();+ const drill = makeSimpleDrill({ count: 1, delayMs: 100 });+ render(+ <PostCognitiveDrillRunner+ drill={drill}+ drillIndex={0}+ drillCount={1}+ onComplete={onComplete}+ isTraining={false}+ />,+ );++ // Let the stimulus reveal (phase -> 'go').+ act(() => {+ vi.advanceTimersByTime(100);+ });+ const goButton = screen.getByRole('button', { name: 'GO!' });++ // Fire two clicks back-to-back within the same synchronous block, before+ // React re-renders in response to the first. The advancingRef guard+ // (checked synchronously, not via state) must reject the second.+ act(() => {+ fireEvent.click(goButton);+ fireEvent.click(goButton);+ });++ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(onComplete).toHaveBeenCalledTimes(1);+ expect(onComplete.mock.calls[0][0].questions).toHaveLength(1);+ });++ it('ignores a keydown response once the result phase has already recorded an answer', () => {+ const onComplete = vi.fn();+ const drill = makeSimpleDrill({ count: 1, delayMs: 100 });+ render(+ <PostCognitiveDrillRunner+ drill={drill}+ drillIndex={0}+ drillCount={1}+ onComplete={onComplete}+ isTraining={false}+ />,+ );++ act(() => {+ vi.advanceTimersByTime(100);+ });+ const goButton = screen.getByRole('button', { name: 'GO!' });++ act(() => {+ fireEvent.click(goButton);+ // A keyboard response racing in immediately after the click, before+ // the 'result' phase has rendered, must not record a second answer.+ fireEvent.keyDown(window, { code: 'Space', key: ' ' });+ });++ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(onComplete).toHaveBeenCalledTimes(1);+ expect(onComplete.mock.calls[0][0].questions).toHaveLength(1);+ });+});