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
fix: make cognitive progression performance-valid (#4446)
Adam Eivy9402723ec41f
diff --git a/.changelog/next/fixed-issue-4446.md b/.changelog/next/fixed-issue-4446.mdnew file mode 100644index 0000000000..fb69f4ec7b--- /dev/null+++ b/.changelog/next/fixed-issue-4446.md@@ -0,0 +1 @@+- Cognitive progression now records Schulte mistakes, rejects incomplete mastery runs, applies task-appropriate speed gates, and advances Stroop and mental rotation through meaningful difficulty levels.diff --git a/client/src/components/meatspace/post/DrillQuestionReview.jsx b/client/src/components/meatspace/post/DrillQuestionReview.jsxindex b58b52ffe7..98655f30e5 100644--- a/client/src/components/meatspace/post/DrillQuestionReview.jsx+++ b/client/src/components/meatspace/post/DrillQuestionReview.jsx@@ -322,10 +322,12 @@ function StroopReview({ questions, missed, drillData }) {// trials — false starts and skips are excluded from the baseline so one// anomalous trial can't skew the threshold for the rest).// =============================================================================-function computeOutlierIndices(questions) {+function computeOutlierIndices(questions, type) {const timed = questions.map((q, i) => ({ i, ms: q.responseMs || 0 }))- .filter(({ i }) => !questions[i].falseStart && questions[i].answered != null);+ .filter(({ i }) => !questions[i].falseStart+ && questions[i].answered != null+ && (type === 'reaction-time' || questions[i].correct));const outliers = new Set();if (timed.length < 3) return outliers;const mean = timed.reduce((s, t) => s + t.ms, 0) / timed.length;@@ -339,7 +341,7 @@ function computeOutlierIndices(questions) {function TimingReview({ questions, missed, type }) {const isReaction = type === 'reaction-time';- const outlierIdx = computeOutlierIndices(questions);+ const outlierIdx = computeOutlierIndices(questions, type);return (<div>@@ -347,7 +349,9 @@ function TimingReview({ questions, missed, type }) {<TableShell><thead><tr className="text-gray-500 text-left border-b border-port-border">- <th className="py-1 pr-2 font-medium">#</th>+ <th className="py-1 pr-2 font-medium">{isReaction ? '#' : 'Attempt'}</th>+ {!isReaction && <th className="py-1 pr-2 font-medium">Target</th>}+ {!isReaction && <th className="py-1 pr-2 font-medium">Selected</th>}<th className="py-1 pr-2 font-medium">Status</th><th className="py-1 pl-2 font-medium text-right">Time</th></tr>@@ -372,6 +376,8 @@ function TimingReview({ questions, missed, type }) {return (<tr key={i} className={`border-b border-port-border/30 ${q.correct === false && !q.falseStart ? 'bg-port-error/10' : ''}`}><td className="py-1 pr-2 text-gray-400 font-mono">{i + 1}</td>+ {!isReaction && <td className="py-1 pr-2 text-gray-400 font-mono">{q.expected ?? q.prompt}</td>}+ {!isReaction && <td className="py-1 pr-2 text-gray-400 font-mono">{q.answered ?? '—'}</td>}<td className="py-1 pr-2"><span className={`inline-flex items-center gap-1 ${statusCls}`}><StatusIcon size={12} />diff --git a/client/src/components/meatspace/post/DrillQuestionReview.test.jsx b/client/src/components/meatspace/post/DrillQuestionReview.test.jsxindex 91fef888f7..2f9c3bca44 100644--- a/client/src/components/meatspace/post/DrillQuestionReview.test.jsx+++ b/client/src/components/meatspace/post/DrillQuestionReview.test.jsx@@ -185,6 +185,20 @@ describe('DrillQuestionReview — stroop', () => {});describe('DrillQuestionReview — schulte-table / reaction-time timing review', () => {+ it('shows every Schulte attempt with its target and selected value', () => {+ const questions = [+ { prompt: '1', index: 0, expected: 1, answered: 4, correct: false, responseMs: 300 },+ { prompt: '1', index: 0, expected: 1, answered: 1, correct: true, responseMs: 700 },+ ];+ const { container } = render(<DrillQuestionReview type="schulte-table" questions={questions} />);+ const table = within(container.querySelector('table'));+ expect(table.getByText('Target')).toBeInTheDocument();+ expect(table.getByText('Selected')).toBeInTheDocument();+ expect(table.getByText('Wrong')).toBeInTheDocument();+ expect(table.getAllByText('1').length).toBeGreaterThan(1);+ expect(table.getByText('4')).toBeInTheDocument();+ });+it('flags a response time far above the others as an outlier', () => {const questions = [{ prompt: '1', index: 0, expected: 1, answered: 1, correct: true, responseMs: 500 },diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsxindex 1b89e8d262..a11ddb1134 100644--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx@@ -284,6 +284,27 @@ export function localReactionTimeScore(drill, questions) {return Math.round(latencyScore * (valid.length / questions.length));}+// Pre-save mirror of the Schulte server scorer. Every click is an attempt;+// completion advances only on the ordered correct target, while successful+// target latency (including time spent making wrong taps) drives the speed term.+export function localSchulteMetrics(drill, questions) {+ const list = Array.isArray(questions) ? questions : [];+ const totalCount = Array.isArray(drill?.cells) ? drill.cells.length : 0;+ const correct = list.filter(question => question.correct);+ const attemptCount = list.length;+ const answeredCount = correct.length;+ const errorCount = attemptCount - answeredCount;+ const accuracy = attemptCount ? answeredCount / attemptCount : null;+ const completion = totalCount ? answeredCount / totalCount : null;+ const refMs = 1000 + Math.round(Math.sqrt(totalCount)) * 500;+ const avgResponseMs = answeredCount+ ? Math.round(correct.reduce((sum, question) => sum + Math.min(Math.max(question.responseMs || 0, 0), refMs), 0) / answeredCount)+ : null;+ const speedBonus = avgResponseMs == null || refMs <= 0 ? 0 : Math.max(0, 1 - avgResponseMs / refMs);+ const score = Math.round(((accuracy || 0) * 0.8 + speedBonus * 0.2) * (completion || 0) * 100);+ return { score, accuracy, completion, avgResponseMs, answeredCount, totalCount, attemptCount, errorCount };+}+// 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 }) {@@ -314,11 +335,12 @@ export function buildCognitiveResult({ type, drill, questions, totalMs }) {// balanced accuracy / valid-median latency, issue #2094) so the pre-save// results screen doesn't show a number that jumps on save. Other types keep// the raw-accuracy approximation (server adds only a small speed bonus).+ const schulteMetrics = type === 'schulte-table' ? localSchulteMetrics(drill, questions) : null;const score = type === 'n-back'? localNBackScore(drill, questions): type === 'reaction-time'? localReactionTimeScore(drill, questions)- : localAccuracyScore(questions);+ : schulteMetrics?.score ?? localAccuracyScore(questions);return {module: 'cognitive',type,@@ -326,6 +348,7 @@ export function buildCognitiveResult({ type, drill, questions, totalMs }) {drillData: drill,questions,score,+ ...(schulteMetrics || {}),totalMs,};}@@ -418,6 +441,21 @@ export function scoreMentalRotationTrial({ trial, index, optionIndex, responseMs};}+// SCHULTE — one ordered click event. `expected` is the current target when the+// click happened; wrong selections stay in the stream and do not advance it.+// The server recomputes these fields from event order, so this is feedback data,+// never an authority boundary.+export function scoreSchulteClick({ target, value, responseMs }) {+ return {+ prompt: `${target}`,+ index: target - 1,+ expected: target,+ answered: value,+ correct: value === target,+ responseMs,+ };+}+// =============================================================================// N-BACK — a letter stream; signal when the current letter matches N steps back// =============================================================================@@ -852,7 +890,13 @@ function SchulteTableRunner({ drill, drillIndex, drillCount, onComplete, isTrainconst handleClick = useCallback((value) => {const current = targetRef.current;- if (value !== current) {+ const question = scoreSchulteClick({+ target: current,+ value,+ responseMs: Date.now() - stepStartRef.current,+ });+ questionsRef.current.push(question);+ if (!question.correct) {setFlash(value);clearTimeout(flashTimeoutRef.current);flashTimeoutRef.current = setTimeout(() => setFlash(null), 200);@@ -861,13 +905,6 @@ function SchulteTableRunner({ drill, drillIndex, drillCount, onComplete, isTrain// 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);diff --git a/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx b/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsxindex 07bf40fc0f..9602bd55c9 100644--- a/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx+++ b/client/src/components/meatspace/post/PostCognitiveDrillRunner.test.jsx@@ -2,11 +2,13 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { render, screen, fireEvent, act } from '@testing-library/react';import PostCognitiveDrillRunner, {localAccuracyScore,+ localSchulteMetrics,buildCognitiveResult,buildNBackQuestions,scoreDigitSpanRecall,scoreStroopTrial,scoreMentalRotationTrial,+ scoreSchulteClick,getDrillTutorial,hasSeenDrillTutorial,markDrillTutorialSeen,@@ -89,6 +91,26 @@ describe('buildCognitiveResult', () => {const slow = [{ correct: true, falseStart: false, responseMs: 580 }];expect(buildCognitiveResult({ type: 'reaction-time', drill, questions: slow, totalMs: 1 }).score).toBe(5);});++ it('schulte pre-save metrics include wrong clicks and completion', () => {+ const drill = { type: 'schulte-table', config: { size: 2 }, cells: [2, 1] };+ const questions = [+ scoreSchulteClick({ target: 1, value: 2, responseMs: 100 }),+ scoreSchulteClick({ target: 1, value: 1, responseMs: 400 }),+ scoreSchulteClick({ target: 2, value: 2, responseMs: 500 }),+ ];+ const result = buildCognitiveResult({ type: 'schulte-table', drill, questions, totalMs: 1000 });+ expect(result).toMatchObject({+ accuracy: 2 / 3,+ completion: 1,+ answeredCount: 2,+ totalCount: 2,+ attemptCount: 3,+ errorCount: 1,+ });+ expect(result.score).toBeLessThan(100);+ expect(localSchulteMetrics(drill, questions).score).toBe(result.score);+ });});describe('buildNBackQuestions', () => {@@ -270,6 +292,98 @@ describe('scoreMentalRotationTrial', () => {});});+describe('scoreSchulteClick', () => {+ it('records the selected value against the current target without hiding an error', () => {+ expect(scoreSchulteClick({ target: 3, value: 7, responseMs: 850 })).toEqual({+ prompt: '3',+ index: 2,+ expected: 3,+ answered: 7,+ correct: false,+ responseMs: 850,+ });+ });+});++describe('SchulteTableRunner error recording', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ markDrillTutorialSeen('schulte-table');+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('persists a wrong tap before the successful sequence and does not advance its target', () => {+ const onComplete = vi.fn();+ const drill = { type: 'schulte-table', config: { size: 2 }, cells: [2, 1] };+ render(+ <PostCognitiveDrillRunner+ drill={drill}+ drillIndex={0}+ drillCount={1}+ onComplete={onComplete}+ isTraining={false}+ />,+ );++ fireEvent.click(screen.getByRole('button', { name: '2' }));+ expect(screen.getByText('Find:').parentElement).toHaveTextContent('1');+ fireEvent.click(screen.getByRole('button', { name: '1' }));+ expect(screen.getByText('Find:').parentElement).toHaveTextContent('2');+ fireEvent.click(screen.getByRole('button', { name: '2' }));++ expect(onComplete).toHaveBeenCalledTimes(1);+ const result = onComplete.mock.calls[0][0];+ expect(result.questions.map(q => [q.expected, q.answered, q.correct])).toEqual([+ [1, 2, false],+ [1, 1, true],+ [2, 2, true],+ ]);+ expect(result.errorCount).toBe(1);+ });+});++describe('NBackRunner stimulus timeouts', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ markDrillTutorialSeen('n-back');+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('persists a missed target when its stimulus window expires without a press', () => {+ const onComplete = vi.fn();+ const drill = {+ type: 'n-back',+ config: { n: 1, stimulusMs: 1000 },+ sequence: ['A', 'A', 'B'],+ };+ render(+ <PostCognitiveDrillRunner+ drill={drill}+ drillIndex={0}+ drillCount={1}+ onComplete={onComplete}+ isTraining={false}+ />,+ );++ act(() => {+ vi.advanceTimersByTime(3800); // 800ms pre-roll + all three stimulus windows+ });++ expect(onComplete).toHaveBeenCalledTimes(1);+ expect(onComplete.mock.calls[0][0].questions).toEqual([+ expect.objectContaining({ index: 1, expected: 'match', answered: null, correct: false }),+ expect.objectContaining({ index: 2, expected: 'no-match', answered: null, correct: true }),+ ]);+ });+});+// 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:diff --git a/client/src/components/meatspace/post/PostDrillConfig.jsx b/client/src/components/meatspace/post/PostDrillConfig.jsxindex 18d0f8dff1..934f5f09e1 100644--- a/client/src/components/meatspace/post/PostDrillConfig.jsx+++ b/client/src/components/meatspace/post/PostDrillConfig.jsx@@ -204,11 +204,12 @@ const COGNITIVE_DRILL_META = {label: 'Stroop',desc: 'Name the ink color of a color-word — attention & inhibition',progressive: true,- ladderFields: ['count'],+ ladderFields: ['count', 'incongruentPct'],fields: [{ key: 'count', label: 'Trials', type: 'number', min: 5, max: 40 },+ { key: 'incongruentPct', label: 'Conflicting Trials (%)', type: 'number', min: 0, max: 100 },],- defaults: { enabled: true, progressive: true, count: 15 },+ defaults: { enabled: true, progressive: true, count: 15, incongruentPct: 75 },},'schulte-table': {label: 'Schulte Table',@@ -224,11 +225,17 @@ const COGNITIVE_DRILL_META = {label: 'Mental Rotation',desc: 'Pick the shape that’s the same, just rotated — spatial reasoning',progressive: true,- ladderFields: ['count'],+ ladderFields: ['count', 'rotationComplexity', 'optionCount'],fields: [{ key: 'count', label: 'Trials', type: 'number', min: 4, max: 20 },+ { key: 'rotationComplexity', label: 'Rotation Range', type: 'select', options: [+ { value: 1, label: '90° only' },+ { value: 2, label: '90–180°' },+ { value: 3, label: 'Any rotation' },+ ] },+ { key: 'optionCount', label: 'Answer Options', type: 'number', min: 2, max: 4 },],- defaults: { enabled: true, progressive: true, count: 8 },+ defaults: { enabled: true, progressive: true, count: 8, rotationComplexity: 3, optionCount: 4 },},'reaction-time': {label: 'Reaction Time',@@ -355,6 +362,20 @@ function AdaptiveBadge({ info }) {function ProgressiveBadge({ info, speedGated = false, managedLabel = 'Manual knobs' }) {if (!info || !Array.isArray(info.levels)) return null;const pct = Math.round((info.thresholds?.targetAccuracy ?? 0.9) * 100);+ const current = info.levels.find(level => level.level === info.level) || {};+ const minSamples = info.thresholds?.minSamples ?? 0;+ const gateParts = [+ `${current.samples || 0}/${minSamples} qualifying runs`,+ `${Math.round((current.accuracy || 0) * 100)}%/${pct}% accuracy`,+ ];+ if (info.thresholds?.minCompletion != null) {+ gateParts.push(`${Math.round((current.completion || 0) * 100)}% avg completion`);+ if (current.incompleteSamples > 0) gateParts.push(`${current.incompleteSamples} incomplete excluded`);+ }+ if (current.targetMs != null) {+ gateParts.push(`${current.avgResponseMs > 0 ? (current.avgResponseMs / 1000).toFixed(1) + 's' : '—'}/${(current.targetMs / 1000).toFixed(1)}s speed`);+ }+ const hasSpeedGate = speedGated || current.targetMs != null;return (<div className="mt-3 space-y-1.5"><div className="flex items-center gap-1.5 text-xs text-port-accent">@@ -376,7 +397,7 @@ function ProgressiveBadge({ info, speedGated = false, managedLabel = 'Manual kno))}</div><p className="text-xs text-gray-500">- Advances to the next rung after {speedGated ? `≥${pct}% accuracy and fast responses` : `sustained ≥${pct}% accuracy`} at this one. {managedLabel} {managedLabel.endsWith('s') ? 'are' : 'is'} ignored while progressive is on.+ {gateParts.join(' · ')}. Advances after {hasSpeedGate ? `≥${pct}% accuracy and the speed target` : `sustained ≥${pct}% accuracy`} at this exact rung. {managedLabel} {managedLabel.endsWith('s') ? 'are' : 'is'} ignored while progressive is on.</p></div>);@@ -446,7 +467,7 @@ function DrillCard({ meta, drillConfig, enabled, accent, onToggle, onUpdateField<div className="flex items-center justify-between mb-3 py-2 px-3 bg-port-bg/50 rounded"><div><span className="text-sm text-white">Progressive difficulty</span>- <p className="text-xs text-gray-500">Ramp up from 1×1-digit as you master speed.</p>+ <p className="text-xs text-gray-500">Difficulty rises only after exact-rung mastery.</p></div><buttontype="button"diff --git a/client/src/components/meatspace/post/PostDrillConfig.test.jsx b/client/src/components/meatspace/post/PostDrillConfig.test.jsxindex a6dd6f191b..9757b492e2 100644--- a/client/src/components/meatspace/post/PostDrillConfig.test.jsx+++ b/client/src/components/meatspace/post/PostDrillConfig.test.jsx@@ -82,10 +82,10 @@ beforeEach(() => {type: 'n-back', level: 1, label: '2-back @ 2500ms', atHardest: false, currentMastered: false,levels: [{ level: 0, label: '1-back @ 2500ms', mastered: true },- { level: 1, label: '2-back @ 2500ms', mastered: false },+ { level: 1, label: '2-back @ 2500ms', mastered: false, samples: 2, accuracy: 0.8, completion: 0.9, incompleteSamples: 1 },{ level: 2, label: '3-back @ 2500ms', mastered: false },],- thresholds: { minSamples: 3, targetAccuracy: 0.85 }, windowDays: 30,+ thresholds: { minSamples: 3, targetAccuracy: 0.85, minCompletion: 0.75 }, windowDays: 30,},});getMemoryItems.mockResolvedValue([{@@ -328,6 +328,8 @@ describe('PostDrillConfig', () => {expect(screen.queryByText('Stimulus (ms)')).toBeNull();await waitFor(() => expect(getPostCognitiveProgress).toHaveBeenCalled());await waitFor(() => expect(screen.getByText(/Level 2 of 3 · 2-back @ 2500ms/)).toBeTruthy());+ expect(screen.getByText(/2\/3 qualifying runs/)).toBeTruthy();+ expect(screen.getByText(/1 incomplete excluded/)).toBeTruthy();// `length` is NOT ladder-managed, so it stays visible + editable even under// progressive (only n/stimulusMs are hidden) — the knob is honestly forwarded.expect(screen.getByText('Sequence Length')).toBeTruthy();@@ -342,6 +344,21 @@ describe('PostDrillConfig', () => {expect(updatePostConfig.mock.calls[0][0].cognitive.drillTypes['n-back'].progressive).toBe(false);});+ it('manual Stroop and mental-rotation modes expose meaningful difficulty knobs', async () => {+ await renderConfig(<PostDrillConfig config={config} onSaved={vi.fn()} onBack={vi.fn()} />);+ fireEvent.click(screen.getByRole('switch', { name: 'Progressive difficulty — Stroop' }));+ fireEvent.click(screen.getByRole('switch', { name: 'Progressive difficulty — Mental Rotation' }));+ expect(screen.getByText('Conflicting Trials (%)')).toBeTruthy();+ expect(screen.getByText('Rotation Range')).toBeTruthy();+ expect(screen.getByText('Answer Options')).toBeTruthy();++ fireEvent.click(screen.getByText('Save'));+ await waitFor(() => expect(updatePostConfig).toHaveBeenCalled());+ const cognitive = updatePostConfig.mock.calls[0][0].cognitive.drillTypes;+ expect(cognitive.stroop).toMatchObject({ progressive: false, incongruentPct: 75 });+ expect(cognitive['mental-rotation']).toMatchObject({ progressive: false, rotationComplexity: 3, optionCount: 4 });+ });+it('toggling Adaptive on persists enabled=true', async () => {await renderConfig(<PostDrillConfig config={config} onSaved={vi.fn()} onBack={vi.fn()} />);fireEvent.click(screen.getByRole('switch', { name: 'Adaptive difficulty' }));diff --git a/client/src/components/meatspace/post/PostProgress.jsx b/client/src/components/meatspace/post/PostProgress.jsxindex 302c77c0ac..1782449749 100644--- a/client/src/components/meatspace/post/PostProgress.jsx+++ b/client/src/components/meatspace/post/PostProgress.jsx@@ -7,7 +7,7 @@ import { useNavigate } from 'react-router';import { getPostProgress } from '../../../services/api';import useChartColors from '../../../hooks/useChartColors.js';import { formatDurationMin } from '../../../utils/formatters';-import { DRILL_TO_DOMAIN, domainLabel } from './constants';+import { DRILL_LABELS, DRILL_TO_DOMAIN, domainLabel } from './constants';import { streakGlyph } from '../../../lib/streakGlyph.js';import PostHistory from './PostHistory';@@ -131,7 +131,8 @@ export default function PostProgress({ subtab, onBack }) {const streak = progress?.streak || { current: 0, longest: 0 };const totals = progress?.totals || { minutesTrained: 0, sessions: 0, practiceEntries: 0 };- const mastery = progress?.mastery || { multiplication: null, memoryItems: [], reviews: null };+ const mastery = progress?.mastery || { multiplication: null, cognitive: {}, memoryItems: [], reviews: null };+ const cognitiveMastery = Object.values(mastery.cognitive || {}).filter(Boolean);const dueTotal = (mastery.memoryItems || []).reduce((n, m) => n + (m.dueCount || 0), 0);const reviews = mastery.reviews || null;const hasAny = totals.sessions > 0 || totals.practiceEntries > 0;@@ -277,6 +278,48 @@ export default function PostProgress({ subtab, onBack }) {</div>)}+ {cognitiveMastery.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-lg p-4 xl:col-span-2">+ <h3 className="text-sm font-medium text-gray-400 mb-3">Cognitive Ladders</h3>+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">+ {cognitiveMastery.map(info => {+ const current = (info.levels || []).find(level => level.level === info.level) || {};+ const targetAccuracy = info.thresholds?.targetAccuracy ?? 0;+ const minSamples = info.thresholds?.minSamples ?? 0;+ const action = info.decision?.action || (info.currentMastered ? 'mastered' : 'hold');+ return (+ <div key={info.type} className="rounded-lg border border-port-border/60 bg-port-bg/40 p-3">+ <div className="flex items-center justify-between gap-2">+ <div>+ <div className="text-sm text-white">{DRILL_LABELS[info.type] || info.type}</div>+ <div className="text-xs text-gray-500">Level {info.level + 1} of {info.levels?.length || 0} · {info.label}</div>+ </div>+ <span className={`text-[0.65rem] uppercase tracking-wide px-2 py-0.5 rounded-full ${+ action === 'promote' || action === 'mastered'+ ? 'bg-port-success/15 text-port-success'+ : 'bg-port-warning/15 text-port-warning'+ }`}>+ {action === 'promote' ? 'promoted' : action}+ </span>+ </div>+ <div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs text-gray-400">+ <span>{current.samples || 0}/{minSamples} exact-rung runs</span>+ <span>{Math.round((current.accuracy || 0) * 100)}% / {Math.round(targetAccuracy * 100)}% accuracy</span>+ {info.thresholds?.minCompletion != null && (+ <span>{Math.round((current.completion || 0) * 100)}% avg completion (≥{Math.round(info.thresholds.minCompletion * 100)}% qualifies)</span>+ )}+ {current.incompleteSamples > 0 && <span>{current.incompleteSamples} incomplete excluded</span>}+ {current.targetMs != null && (+ <span>{current.avgResponseMs > 0 ? `${(current.avgResponseMs / 1000).toFixed(1)}s` : '—'} / ≤{(current.targetMs / 1000).toFixed(1)}s</span>+ )}+ </div>+ </div>+ );+ })}+ </div>+ </div>+ )}+<div className="bg-port-card border border-port-border rounded-lg p-4"><div className="flex items-center justify-between mb-3"><h3 className="text-sm font-medium text-gray-400">Memory Mastery</h3>diff --git a/client/src/components/meatspace/post/PostProgress.test.jsx b/client/src/components/meatspace/post/PostProgress.test.jsxindex 10b51f9aff..a31cb1086f 100644--- a/client/src/components/meatspace/post/PostProgress.test.jsx+++ b/client/src/components/meatspace/post/PostProgress.test.jsx@@ -34,6 +34,19 @@ const PROGRESS = {streak: { current: 3, longest: 5, lastActiveDate: '2026-06-03' },mastery: {multiplication: { level: 2, description: '1×1×1-digit', floorLevel: 1 },+ cognitive: {+ stroop: {+ type: 'stroop',+ level: 1,+ label: '12 trials · 65% incongruent',+ levels: [+ { level: 0, samples: 3, accuracy: 0.9, completion: 1, incompleteSamples: 0, avgResponseMs: 1350, targetMs: 1500 },+ { level: 1, samples: 2, accuracy: 0.88, completion: 0.92, incompleteSamples: 1, avgResponseMs: 1450, targetMs: 1400 },+ ],+ thresholds: { minSamples: 3, targetAccuracy: 0.85, minCompletion: 0.75 },+ decision: { action: 'hold', reasons: ['samples', 'speed'] },+ },+ },memoryItems: [{ id: 'm1', title: 'Elements', overallPct: 42, dueCount: 1 }],},};@@ -62,9 +75,14 @@ describe('PostProgress', () => {expect(screen.getByText('Score Trend')).toBeInTheDocument();expect(screen.getByText('Accuracy Trend')).toBeInTheDocument();expect(screen.getByText(/Response Time/)).toBeInTheDocument();- // Mastery panel: multiplication rung + memory item.+ // Mastery panel: multiplication + performance-valid cognitive rung + memory.expect(screen.getByText('Multiplication Ladder')).toBeInTheDocument();expect(screen.getByText('L2')).toBeInTheDocument();+ expect(screen.getByText('Cognitive Ladders')).toBeInTheDocument();+ expect(screen.getByText('Stroop')).toBeInTheDocument();+ expect(screen.getByText('2/3 exact-rung runs')).toBeInTheDocument();+ expect(screen.getByText('1 incomplete excluded')).toBeInTheDocument();+ expect(screen.getByText('1.4s / ≤1.4s')).toBeInTheDocument();expect(screen.getByText('Elements')).toBeInTheDocument();});@@ -82,7 +100,7 @@ describe('PostProgress', () => {series: { byDay: [], byDomain: {}, byDrill: {} },totals: { minutesTrained: 0, sessions: 0, practiceEntries: 0 },streak: { current: 0, longest: 0, lastActiveDate: null },- mastery: { multiplication: null, memoryItems: [] },+ mastery: { multiplication: null, cognitive: {}, memoryItems: [] },});renderProgress();await waitFor(() => expect(screen.getByText(/No training activity yet/)).toBeInTheDocument());diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsxindex 3461fc1c6f..ab548b2d0a 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx@@ -54,6 +54,8 @@ export function cognitiveSummary(type, cfg) {if (type === 'n-back') return `${cfg.n ?? 2}-back`;if (type === 'digit-span') return `${cfg.startLength ?? 3}–${cfg.maxLength ?? 8}`;if (type === 'schulte-table') return `${cfg.size ?? 5}×${cfg.size ?? 5}`;+ if (type === 'stroop') return `${cfg.incongruentPct ?? 75}% conflict`;+ if (type === 'mental-rotation') return `${cfg.optionCount ?? 4} options`;if (type === 'reaction-time') return `${cfg.count ?? 15} trials (${cfg.mode ?? 'simple'})`;return cfg.count ? `${cfg.count} trials` : '';}@@ -254,7 +256,10 @@ export default function PostSessionLauncher({maxLength: cfg.maxLength,showMs: cfg.showMs,count: cfg.count,+ incongruentPct: cfg.incongruentPct,size: cfg.size,+ rotationComplexity: cfg.rotationComplexity,+ optionCount: cfg.optionCount,mode: cfg.mode,minDelayMs: cfg.minDelayMs,maxDelayMs: cfg.maxDelayMs,diff --git a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx b/client/src/components/meatspace/post/PostSessionLauncher.test.jsxindex d7a09c71dd..bd7ec0447d 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.test.jsx@@ -79,12 +79,18 @@ describe('cognitiveSummary', () => {expect(cognitiveSummary('reaction-time', { count: 20, mode: 'choice' })).toBe('20 trials (choice)');});- it('falls back to "<count> trials" for an unrecognized type with a count', () => {- expect(cognitiveSummary('stroop', { count: 10 })).toBe('10 trials');+ it('summarizes the Stroop interference mix', () => {+ expect(cognitiveSummary('stroop', {})).toBe('75% conflict');+ expect(cognitiveSummary('stroop', { incongruentPct: 90 })).toBe('90% conflict');+ });++ it('summarizes mental-rotation option complexity', () => {+ expect(cognitiveSummary('mental-rotation', {})).toBe('4 options');+ expect(cognitiveSummary('mental-rotation', { optionCount: 3 })).toBe('3 options');});- it('falls back to an empty string for an unrecognized type with no count', () => {- expect(cognitiveSummary('mental-rotation', {})).toBe('');+ it('falls back to "<count> trials" for an unrecognized type with a count', () => {+ expect(cognitiveSummary('future-cognitive-drill', { count: 10 })).toBe('10 trials');});});diff --git a/client/src/components/meatspace/post/PostSessionResults.test.jsx b/client/src/components/meatspace/post/PostSessionResults.test.jsxindex 1e505eaab6..b411e412ca 100644--- a/client/src/components/meatspace/post/PostSessionResults.test.jsx+++ b/client/src/components/meatspace/post/PostSessionResults.test.jsx@@ -81,6 +81,26 @@ describe('PostSessionResults drill breakdown', () => {expect(screen.queryByText('6 x 7')).not.toBeInTheDocument();});+ it('surfaces wrong Schulte taps in the saved-performance summary', () => {+ renderResults({+ drillResults: [{+ type: 'schulte-table',+ score: 72,+ accuracy: 2 / 3,+ completion: 1,+ avgResponseMs: 1200,+ errorCount: 1,+ questions: [+ { prompt: '1', expected: 1, answered: 2, correct: false, responseMs: 400 },+ { prompt: '1', expected: 1, answered: 1, correct: true, responseMs: 700 },+ { prompt: '2', expected: 2, answered: 2, correct: true, responseMs: 1200 },+ ],+ }],+ });++ expect(screen.getByText(/67% acc · 1 error · 1\.2s/)).toBeInTheDocument();+ });+it('collapses the review again on a second click', () => {const { container } = renderResults();const row = screen.getByText('Multiplication');diff --git a/client/src/components/meatspace/post/PostSessionSummary.jsx b/client/src/components/meatspace/post/PostSessionSummary.jsxindex 65d6b34889..10fff4f537 100644--- a/client/src/components/meatspace/post/PostSessionSummary.jsx+++ b/client/src/components/meatspace/post/PostSessionSummary.jsx@@ -101,6 +101,10 @@ export default function PostSessionSummary({ drillResults = [], sessionScore = 0: (timed.length > 0 ? Math.round(timed.reduce((s, q) => s + q.responseMs, 0) / timed.length) : null);const parts = [];if (accPct != null) parts.push(`${accPct}% acc`);+ if (result.type === 'schulte-table') {+ const errorCount = result.errorCount ?? questions.filter(q => q.correct === false).length;+ parts.push(`${errorCount} ${errorCount === 1 ? 'error' : 'errors'}`);+ }if (avgMs != null) parts.push(`${(avgMs / 1000).toFixed(1)}s`);if (compPct != null && compPct < 100) parts.push(`${compPct}% done`);subtitle = parts.join(' · ') || `${questions.length} questions`;diff --git a/server/lib/README.md b/server/lib/README.mdindex bc0ec5cd05..2ee41463c4 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -305,7 +305,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `postAdaptive.js` | Pure POST adaptive-difficulty policy — nudges a math drill's primary knob (`steps`/`maxDigits`/`maxExponent`/`tolerancePct`) up/down within clamped bounds from recent scored performance. Opt-in via the config Adaptive toggle. || `postMultiplicationLadder.js` | Pure progressive multiplication ladder — mastery-gated difficulty rungs (`[1,1]` → `[1,2]` → `[1,1,1]` → …). Resolves the user's current level from per-level speed+accuracy stats so the plain multiplication drill ramps up instead of starting at a fixed hard difficulty. On by default. Built on `postProgression.js`. || `postPowersLadder.js` | Pure technique-anchored Powers ladder — cumulative named-method pools, full supported-pair registry, and speed+accuracy mastery progression built on `postProgression.js`. |-| `postProgression.js` | Generic mastery-gated progression ladder (extracted from `postMultiplicationLadder.js`) — `createProgression({ levels, describeLevel, speedTargetForLevel? })` resolves a user's current rung from per-level stats with an anti-demotion floor. Also defines the cognitive-drill ladders (n-back / digit-span / schulte / mental-rotation / stroop) and their level→generator-config mapping. |+| `postProgression.js` | Generic mastery-gated progression ladder (extracted from `postMultiplicationLadder.js`) — `createProgression({ levels, describeLevel, speedTargetForLevel? })` resolves a user's current rung from exact-level sample, accuracy, completion, and optional speed evidence with an anti-demotion floor. Also defines meaningful cognitive-drill ladders (n-back / digit-span / Schulte / mental rotation / Stroop) and their level→generator-config mapping. || `spacedRepetition.js` | The shared SM-2-inspired review scheduler, extracted from `services/meatspacePostMemory.js` when SongBook practice became its second consumer (#4102). One four-field schedule shape (`{ ease, intervalDays, nextReview, lastReviewed }`, no `repetitions` counter — the 0 → 1 → 6 → `round(prev * ease)` ladder derives from the previous interval, so a schedule round-trips through import/export/federation on those four fields alone). `advanceSchedule(schedule, ratio, now)` is the core (ease clamped to `MIN_EASE`..`MAX_EASE`, interval capped at `MAX_INTERVAL_DAYS` so `new Date(now + interval*DAY)` can't overflow into an Invalid Date; quality < 3 zeroes the interval to resurface the record but still applies the ease penalty). `mergeScheduleAdvance(prev, advanced, now)` gates interval GROWTH to once per review day (a shrink always applies) for UIs that submit per chunk/section; `isSameReviewDay` is that gate's own predicate, reusable by callers gating their own once-a-day progression. `scheduleOrDefault(record, schedule?)` is the read-path fallback — a record with no schedule derives one anchored to its `updatedAt`/`createdAt` (stable and in the past → due now), so "due" can't flap between two reads a millisecond apart. `ratioToQuality` / `qualityToRatio` are exact inverses over the integers, so a self-graded 0..5 review lands on the quality the user picked. `isScheduleDue` treats an absent/unparseable `nextReview` as due — a record we can't schedule is one to surface, never one to hide forever. Pure. || `songPractice.js` | SongBook repertoire practice scheduling (#4102) — the pure core behind `POST /api/brain/songbook/:id/practice`. `applySongPractice(song, quality, now)` → `{ stage, practice }`, the exact partial to hand `brainStorage.updateWith`: it advances the shared `spacedRepetition` schedule from a 0..5 self-grade and moves the song's `stage` along `SONG_STAGE_ORDER` (≥ `SONG_PROMOTE_MIN_QUALITY` promotes, ≤ `SONG_REGRESS_MAX_QUALITY` regresses, a 3 holds). Promotion is gated to once per practice day (regression never is), and a practiced song floors at `learning` — `new` means "never picked up", which stops being true after one session. `songPracticeOrDefault(song)` derives the schedule on READ for every song predating the feature (nothing is backfilled to disk: a migration would restamp `updatedAt` on every record and spray federation churn, and would break the `data.reference/` seeds' byte-identity). `nextSongStage` no-ops on a stage this install doesn't recognize, so a practice log can't rewrite a value synced from a newer peer. `isSongDue(song, now)` mirrors the client's `songDueAt` in `client/src/components/songbook/constants.js`. Pure. || `postTopics.js` | Pure POST practice-topic registry — `POST_TOPICS` (`{ id, label, module, surface, drillTypes }`) is the single source of truth for "what am I studying?", plus `resolveTopicForDrillType` / `isTopicEnabled` / `isMemoryItemEnabled`. Gates session composition and recommendations, including Memory's composed and dedicated practice routes plus standalone Morse. Mirrored to the client's post `constants.js` (parity test). |diff --git a/server/lib/postProgression.js b/server/lib/postProgression.jsindex 2abb924861..304a8fd029 100644--- a/server/lib/postProgression.js+++ b/server/lib/postProgression.js@@ -26,9 +26,8 @@* requires the level's average response time to clear the target, and a level* with no timed samples is never "instantly mastered") — this is the* multiplication behaviour. A ladder without it is *accuracy-only*: mastery is- * purely samples + accuracy, which is what the cognitive drills use (their- * difficulty ramp lives in the rung knobs — a higher n, a longer span, a bigger- * grid — not in a per-question speed bar).+ * purely samples + accuracy. Cognitive ladders opt into the speed gate only+ * where response latency is part of the trained skill (Schulte and Stroop).*/// Shared mastery thresholds. Ladder definitions override any subset via@@ -84,11 +83,13 @@ export function createProgression(def) {const samples = Number.isFinite(stat?.samples) ? stat.samples : 0;const accuracy = Number.isFinite(stat?.accuracy) ? stat.accuracy : 0;const avgResponseMs = Number.isFinite(stat?.avgResponseMs) ? stat.avgResponseMs : 0;+ const timedSamples = Number.isFinite(stat?.timedSamples) ? stat.timedSamples : avgResponseMs > 0 ? samples : 0;if (samples < options.minSamples) return false;if (accuracy < options.targetAccuracy) return false;const target = speedTargetForLevel ? speedTargetForLevel(clamp(level), options) : null;if (target != null && Number.isFinite(target) && target > 0) {// avgResponseMs of 0 means no timed samples — never "instant mastery".+ if (timedSamples < options.minSamples) return false;if (avgResponseMs <= 0) return false;return avgResponseMs <= target;}@@ -107,18 +108,26 @@ export function createProgression(def) {const rungs = levels.map((descriptor, level) => {const stat = levelStats?.[level] || levelStats?.[String(level)] || {};const samples = Number.isFinite(stat.samples) ? stat.samples : 0;+ const attempts = Number.isFinite(stat.attempts) ? stat.attempts : samples;const accuracy = Number.isFinite(stat.accuracy) ? stat.accuracy : 0;+ const completion = Number.isFinite(stat.completion) ? stat.completion : 0;+ const incompleteSamples = Number.isFinite(stat.incompleteSamples) ? stat.incompleteSamples : 0;const avgResponseMs = Number.isFinite(stat.avgResponseMs) ? stat.avgResponseMs : 0;+ const timedSamples = Number.isFinite(stat.timedSamples) ? stat.timedSamples : avgResponseMs > 0 ? samples : 0;const targetMs = speedTargetForLevel ? speedTargetForLevel(level, options) : null;return {level,descriptor,label: def.describeLevel(level),samples,+ attempts,accuracy,+ completion,+ incompleteSamples,avgResponseMs,+ timedSamples,targetMs,- mastered: isLevelMastered({ samples, accuracy, avgResponseMs }, level, options),+ mastered: isLevelMastered({ samples, accuracy, avgResponseMs, timedSamples }, level, options),};});@@ -168,10 +177,10 @@ export function createProgression(def) {// the config/preview badge. reaction-time is deliberately absent — it's a// measurement baseline, not a skill ladder.//-// Mastery is accuracy-only (no per-question speed gate): the difficulty ramp is-// the knob itself (higher n, faster stimulus, longer span, bigger grid, more-// trials), so "mastered this rung" means sustained high accuracy AT that knob-// setting. For n-back the accuracy stamped per task is the balanced /+// Mastery always uses exact-rung samples + accuracy + completion-qualified+// runs. Schulte and Stroop additionally gate on average response latency because+// speed/response pressure is part of those skills; the other ladders deliberately+// remain accuracy-only. For n-back the accuracy stamped per task is the balanced// signal-detection accuracy from #2094, so the do-nothing exploit can't bank a// rung.@@ -187,6 +196,7 @@ export const COGNITIVE_MASTERY_DEFAULTS = {// (n-back completion is always 1 — go/no-go — so this never gates it.)minCompletion: 0.75,windowDays: 30,+ responseMsCap: 120000,};export const COGNITIVE_LADDERS = {@@ -223,26 +233,30 @@ export const COGNITIVE_LADDERS = {{ size: 6 },],describe: rung => `${rung.size}×${rung.size}`,+ speedTargetsMs: [2500, 3000, 3500],},- // Spatial reasoning: more trials per run (time pressure via volume).+ // Spatial reasoning: add transformation range and mirrored visual competition.+ // Run length may rise too, but it is never the sole difficulty change.'mental-rotation': {levels: [- { count: 6 },- { count: 8 },- { count: 10 },- { count: 12 },+ { count: 6, rotationComplexity: 1, optionCount: 2 },+ { count: 6, rotationComplexity: 2, optionCount: 3 },+ { count: 8, rotationComplexity: 3, optionCount: 3 },+ { count: 8, rotationComplexity: 3, optionCount: 4 },],- describe: rung => `${rung.count} trials`,+ describe: rung => `${rung.rotationComplexity === 1 ? '90°' : rung.rotationComplexity === 2 ? '90–180°' : 'any rotation'} · ${rung.optionCount} options`,},- // Attention/inhibition: more trials per run.+ // Attention/inhibition: raise the proportion of conflicting word/ink trials.+ // Count can vary for evidence volume, but conflict is the real rung lever.'stroop': {levels: [- { count: 10 },- { count: 15 },- { count: 20 },- { count: 25 },+ { count: 10, incongruentPct: 50 },+ { count: 12, incongruentPct: 65 },+ { count: 15, incongruentPct: 80 },+ { count: 18, incongruentPct: 90 },],- describe: rung => `${rung.count} trials`,+ describe: rung => `${rung.incongruentPct}% conflict · ${rung.count} trials`,+ speedTargetsMs: [1500, 1400, 1300, 1200],},};@@ -261,7 +275,9 @@ export function cognitiveProgression(type) {levels: ladder.levels,describeLevel: level => ladder.describe(ladder.levels[level]),mastery: COGNITIVE_MASTERY_DEFAULTS,- // No speedTargetForLevel → accuracy-only mastery.+ ...(Array.isArray(ladder.speedTargetsMs) && {+ speedTargetForLevel: level => ladder.speedTargetsMs[level],+ }),});}return cognitiveProgressions[type];@@ -292,14 +308,53 @@ export function resolveCognitiveProgression(type, levelStats = {}, floorLevel =const prog = cognitiveProgression(type);if (!prog) return null;const res = prog.resolveLevel(levelStats, {}, floorLevel);+ const levels = res.levels.map(rung => ({+ ...rung,+ criteria: {+ samples: {+ actual: rung.samples,+ target: COGNITIVE_MASTERY_DEFAULTS.minSamples,+ met: rung.samples >= COGNITIVE_MASTERY_DEFAULTS.minSamples,+ },+ accuracy: {+ actual: rung.accuracy,+ target: COGNITIVE_MASTERY_DEFAULTS.targetAccuracy,+ met: rung.accuracy >= COGNITIVE_MASTERY_DEFAULTS.targetAccuracy,+ },+ completion: {+ actual: rung.completion,+ target: COGNITIVE_MASTERY_DEFAULTS.minCompletion,+ excluded: rung.incompleteSamples,+ },+ speed: rung.targetMs == null ? null : {+ actualMs: rung.avgResponseMs,+ targetMs: rung.targetMs,+ timedSamples: rung.timedSamples,+ met: rung.timedSamples >= COGNITIVE_MASTERY_DEFAULTS.minSamples+ && rung.avgResponseMs > 0+ && rung.avgResponseMs <= rung.targetMs,+ },+ },+ }));+ const current = levels[res.level];+ const reasons = [];+ if (current.samples < COGNITIVE_MASTERY_DEFAULTS.minSamples) reasons.push('samples');+ if (current.accuracy < COGNITIVE_MASTERY_DEFAULTS.targetAccuracy) reasons.push('accuracy');+ if (current.targetMs != null && !current.criteria.speed.met) reasons.push('speed');return {...res,+ levels,type,config: cognitiveLevelConfig(type, res.level),windowDays: COGNITIVE_MASTERY_DEFAULTS.windowDays,+ decision: {+ action: res.level > res.floorLevel ? 'promote' : res.atHardest && res.currentMastered ? 'mastered' : 'hold',+ reasons,+ },thresholds: {minSamples: COGNITIVE_MASTERY_DEFAULTS.minSamples,targetAccuracy: COGNITIVE_MASTERY_DEFAULTS.targetAccuracy,+ minCompletion: COGNITIVE_MASTERY_DEFAULTS.minCompletion,},};}diff --git a/server/lib/postProgression.test.js b/server/lib/postProgression.test.jsindex fda765ff2b..59226e5f89 100644--- a/server/lib/postProgression.test.js+++ b/server/lib/postProgression.test.js@@ -123,6 +123,14 @@ describe('cognitive ladders', () => {expect(l[l.length - 1]).toMatchObject({ direction: 'backward', maxLength: 9 });});+ it('stroop and mental-rotation rungs change real task difficulty, not only run length', () => {+ const stroop = COGNITIVE_LADDERS.stroop.levels;+ expect(stroop.map(r => r.incongruentPct)).toEqual([50, 65, 80, 90]);+ const rotation = COGNITIVE_LADDERS['mental-rotation'].levels;+ expect(rotation.map(r => r.rotationComplexity)).toEqual([1, 2, 3, 3]);+ expect(rotation.map(r => r.optionCount)).toEqual([2, 3, 3, 4]);+ });+it('cognitiveLevelConfig returns the clamped rung knobs (a fresh copy)', () => {expect(cognitiveLevelConfig('n-back', 0)).toEqual({ n: 1, stimulusMs: 2500 });expect(cognitiveLevelConfig('n-back', 99)).toEqual({ n: 3, stimulusMs: 1600 });@@ -140,7 +148,11 @@ describe('cognitive ladders', () => {expect(r.level).toBe(0);expect(r.config).toEqual({ n: 1, stimulusMs: 2500 });expect(r.label).toBe('1-back @ 2500ms');- expect(r.thresholds).toEqual({ minSamples: COGNITIVE_MASTERY_DEFAULTS.minSamples, targetAccuracy: COGNITIVE_MASTERY_DEFAULTS.targetAccuracy });+ expect(r.thresholds).toEqual({+ minSamples: COGNITIVE_MASTERY_DEFAULTS.minSamples,+ targetAccuracy: COGNITIVE_MASTERY_DEFAULTS.targetAccuracy,+ minCompletion: COGNITIVE_MASTERY_DEFAULTS.minCompletion,+ });expect(r.levels).toHaveLength(5);});@@ -151,6 +163,21 @@ describe('cognitive ladders', () => {expect(r.config).toEqual({ n: 3, stimulusMs: 2500 });});+ it('speed-gated cognitive skills require enough exact-rung timed samples under the target', () => {+ const slow = resolveCognitiveProgression('schulte-table', {+ 0: { samples: 3, timedSamples: 3, accuracy: 1, avgResponseMs: 3000 },+ }, 0);+ expect(slow.level).toBe(0);+ expect(slow.levels[0].criteria.speed.met).toBe(false);+ expect(slow.decision).toMatchObject({ action: 'hold', reasons: ['speed'] });++ const fast = resolveCognitiveProgression('schulte-table', {+ 0: { samples: 3, timedSamples: 3, accuracy: 1, avgResponseMs: 2000 },+ }, 0);+ expect(fast.level).toBe(1);+ expect(fast.decision.action).toBe('promote');+ });+it('resolveCognitiveProgression is null for a non-laddered type', () => {expect(resolveCognitiveProgression('reaction-time', {}, 0)).toBeNull();});diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex 9a968e03ca..584232efa4 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -141,6 +141,9 @@ const drillTypeConfigSchema = z.object({maxLength: z.number().int().min(3).max(12).optional(),// --- Cognitive drill knobs (schulte-table / mental-rotation / reaction-time) ---size: z.number().int().min(3).max(7).optional(),+ incongruentPct: z.number().int().min(0).max(100).optional(),+ rotationComplexity: z.number().int().min(1).max(3).optional(),+ optionCount: z.number().int().min(2).max(4).optional(),mode: z.enum(['simple', 'choice']).optional(),minDelayMs: z.number().int().min(300).max(5000).optional(),maxDelayMs: z.number().int().min(300).max(8000).optional(),@@ -174,6 +177,8 @@ const taskResultSchema = z.object({avgResponseMs: z.number().min(0).nullable().optional(),answeredCount: z.number().int().min(0).optional(),totalCount: z.number().int().min(0).optional(),+ attemptCount: z.number().int().min(0).optional(),+ errorCount: z.number().int().min(0).optional(),medianMs: z.number().min(0).nullable().optional(),bestMs: z.number().min(0).nullable().optional(),span: z.number().int().min(0).optional(),diff --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.jsindex 51b93287ab..464da8c735 100644--- a/server/lib/postValidation.test.js+++ b/server/lib/postValidation.test.js@@ -220,6 +220,23 @@ describe('questionResultSchema chunkId/element (issue #2016)', () => {});});+describe('postSessionSubmitSchema Schulte evidence metrics', () => {+ it('preserves server-recomputed attempt and error counts on the task shape', () => {+ const parsed = postSessionSubmitSchema.parse({+ modules: ['cognitive'],+ tasks: [{+ module: 'cognitive',+ type: 'schulte-table',+ questions: [{ prompt: '1', index: 0, expected: 1, answered: 2, correct: false, responseMs: 300 }],+ attemptCount: 2,+ errorCount: 1,+ totalMs: 300,+ }],+ });+ expect(parsed.tasks[0]).toMatchObject({ attemptCount: 2, errorCount: 1 });+ });+});+describe('postSessionSubmitSchema.modules — enum of known modules (issue #2099, fix #6)', () => {// Regression: `modules` (session-level) and each task's `module` were both// z.array(z.string())/z.string() — any typo'd string passed validation and@@ -366,12 +383,26 @@ describe('drillTypeConfigSchema numeric bounds', () => {expect(() => postDrillRequestSchema.parse({ type: 'estimation', config: { tolerancePct: 51 } })).toThrow();});- it('accepts cognitive-drill knobs within bounds (n, length, size, choices)', () => {+ it('accepts cognitive-drill knobs within bounds', () => {const parsed = postDrillRequestSchema.parse({- type: 'n-back',- config: { n: 3, length: 60, size: 7, choices: 4 },+ type: 'mental-rotation',+ config: { n: 3, length: 60, size: 7, choices: 4, incongruentPct: 90, rotationComplexity: 3, optionCount: 4 },+ });+ expect(parsed.config).toMatchObject({+ n: 3,+ length: 60,+ size: 7,+ choices: 4,+ incongruentPct: 90,+ rotationComplexity: 3,+ optionCount: 4,});- expect(parsed.config).toMatchObject({ n: 3, length: 60, size: 7, choices: 4 });+ });++ it('rejects out-of-range interference and rotation complexity knobs', () => {+ expect(() => postDrillRequestSchema.parse({ type: 'stroop', config: { incongruentPct: 101 } })).toThrow();+ expect(() => postDrillRequestSchema.parse({ type: 'mental-rotation', config: { rotationComplexity: 4 } })).toThrow();+ expect(() => postDrillRequestSchema.parse({ type: 'mental-rotation', config: { optionCount: 1 } })).toThrow();});it('rejects an out-of-range n-back n (must be 1-3)', () => {diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex a56ec5d749..5431266ae9 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -108,9 +108,9 @@ const DEFAULT_CONFIG = {drillTypes: {'n-back': { enabled: true, progressive: true, n: 2, length: 20, stimulusMs: 2500 },'digit-span': { enabled: true, progressive: true, direction: 'forward', startLength: 3, maxLength: 8, showMs: 1000 },- 'stroop': { enabled: true, progressive: true, count: 15 },+ 'stroop': { enabled: true, progressive: true, count: 15, incongruentPct: 75 },'schulte-table': { enabled: true, progressive: true, size: 5 },- 'mental-rotation': { enabled: true, progressive: true, count: 8 },+ 'mental-rotation': { enabled: true, progressive: true, count: 8, rotationComplexity: 3, optionCount: 4 },'reaction-time': { enabled: true, mode: 'simple', count: 15, minDelayMs: 1000, maxDelayMs: 3000, choices: 3 }}},@@ -297,7 +297,8 @@ export async function submitPostSession(sessionData) {const {score: _score, correct: _correct,accuracy: _acc, completion: _comp, avgResponseMs: _avg,- answeredCount: _ac, totalCount: _tc, medianMs: _med, bestMs: _best, span: _span,+ answeredCount: _ac, totalCount: _tc, attemptCount: _attempts, errorCount: _errors,+ medianMs: _med, bestMs: _best, span: _span,hits: _h, misses: _m, falseAlarms: _fa, correctRejections: _cr,...rest} = t || {};@@ -797,7 +798,7 @@ function finalizeMetricSeries(map) {* practice-entry count over the window.* - `streak` ONE unified streak (sessions OR training-log activity),* computed over ALL history like `getPostStats`.- * - `mastery` multiplication ladder rung + memory items (mastery/due).+ * - `mastery` multiplication/cognitive ladder evidence + memory items.** Accuracy/speed are reported separately (issue #2094): the persisted per-task* `accuracy`/`avgResponseMs` are preferred, with a per-question derivation@@ -894,16 +895,20 @@ export async function getPostProgress({ days = 90 } = {}) {const sessionMs = sessions.reduce((sum, s) => sum + (s.durationMs || 0), 0);const trainingMs = training.reduce((sum, e) => sum + (e.totalMs || 0), 0);- // Mastery block: multiplication ladder rung + per-item memory mastery/due.- const mulProgress = await getMultiplicationProgress();- const memoryItems = await getMemoryItems();- const dueItems = await getDueMemoryItems();+ // Mastery block: multiplication + cognitive ladder evidence and per-item+ // memory mastery/due. Cognitive entries retain every exact-rung measure used+ // to promote or hold so the Progress UI can explain the decision.+ const [mulProgress, cognitiveProgress, memoryItems, dueItems, reviews] = await Promise.all([+ getMultiplicationProgress(),+ getCognitiveProgress(),+ getMemoryItems(),+ getDueMemoryItems(),+ getRetentionReport(new Date()),+ ]);const dueIds = new Set(dueItems.map(i => i.id));// Skill re-verification retention state (issue #2096): per-skill fresh / due /// needs-refresh + a 90-day retention %. Empty on fresh installs (nothing// tracked until the first skill is mastered).- const reviews = await getRetentionReport(new Date());-return {days: window,series: {@@ -923,6 +928,7 @@ export async function getPostProgress({ days = 90 } = {}) {description: mulProgress.label,floorLevel: mulProgress.floorLevel,},+ cognitive: cognitiveProgress,memoryItems: memoryItems.map(it => ({id: it.id,title: it.title,@@ -1704,17 +1710,16 @@ export async function getPowersProgress() {/*** Aggregate a laddered cognitive drill's performance per level from scored- * history so its ladder can decide whether each rung is mastered. Cognitive- * mastery is accuracy-only, and a "sample" is one completed drill (not one- * answered question) — so each task contributes its stamped level and its- * task-level `accuracy` (the balanced/SDT accuracy for n-back, #2094; the- * answered accuracy elsewhere), which is what a raw per-question ratio can't- * express (it would reward n-back's do-nothing exploit).+ * history so its ladder can decide whether each rung is mastered. A "sample"+ * is one completion-qualified drill (not one answered question), bucketed by+ * its exact stamped level. Each task contributes task-level accuracy (balanced+ * SDT accuracy for n-back, #2094) and response latency for the two speed-gated+ * skills. Incomplete attempts remain visible but do not bank mastery samples.** Returns the windowed per-level stats plus the all-time `floorLevel` (the* highest rung ever reached), the anti-demotion signal for resolveLevel.*- * @returns {Promise<{stats: Record<number, {samples,accuracy,avgResponseMs}>, floorLevel: number}>}+ * @returns {Promise<{stats: Record<number, {samples,attempts,accuracy,completion,incompleteSamples,avgResponseMs}>, floorLevel: number}>}*/async function getCognitiveLevelStats(type, windowDays = COGNITIVE_MASTERY_DEFAULTS.windowDays) {const atDate = new Date();@@ -1739,24 +1744,49 @@ async function getCognitiveLevelStats(type, windowDays = COGNITIVE_MASTERY_DEFAU// Mastery stats are windowed.const date = recordDayKey(session, timezone);if (cutoffStr && (!date || date < cutoffStr)) continue;- const acc = Number.isFinite(task.accuracy) ? task.accuracy : null;- if (acc == null) continue;+ const acc = deriveTaskAccuracy(task);+ const derivedComp = deriveTaskCompletion(task);+ const comp = derivedComp == null ? 1 : derivedComp;+ const bucket = byLevel[level] || (byLevel[level] = {+ attempts: 0,+ samples: 0,+ incompleteSamples: 0,+ accSum: 0,+ completionSum: 0,+ responseSamples: 0,+ totalResponseMs: 0,+ });+ bucket.attempts += 1;+ bucket.completionSum += comp;// Skip low-completion runs: accuracy is answered-only, so a run that// leaves the harder trials blank must not bank a high-accuracy sample and// promote the rung (issue #2095 review). A null completion (legacy tasks)// is treated as complete so old history still counts.- const comp = Number.isFinite(task.completion) ? task.completion : null;- if (comp != null && comp < COGNITIVE_MASTERY_DEFAULTS.minCompletion) continue;- const bucket = byLevel[level] || (byLevel[level] = { samples: 0, accSum: 0 });+ if (acc == null || comp < COGNITIVE_MASTERY_DEFAULTS.minCompletion) {+ bucket.incompleteSamples += 1;+ continue;+ }bucket.samples += 1;bucket.accSum += acc;+ const responseMs = deriveTaskAvgResponseMs(task);+ if (responseMs != null && responseMs > 0) {+ bucket.responseSamples += 1;+ bucket.totalResponseMs += Math.min(responseMs, COGNITIVE_MASTERY_DEFAULTS.responseMsCap);+ }}}const stats = {};for (const [level, b] of Object.entries(byLevel)) {- // avgResponseMs is 0 (unused) — cognitive mastery is accuracy-only.- stats[level] = { samples: b.samples, accuracy: b.samples ? b.accSum / b.samples : 0, avgResponseMs: 0 };+ stats[level] = {+ samples: b.samples,+ attempts: b.attempts,+ accuracy: b.samples ? b.accSum / b.samples : 0,+ completion: b.attempts ? b.completionSum / b.attempts : 0,+ incompleteSamples: b.incompleteSamples,+ timedSamples: b.responseSamples,+ avgResponseMs: b.responseSamples ? b.totalResponseMs / b.responseSamples : 0,+ };}return { stats, floorLevel };}@@ -1840,8 +1870,9 @@ export async function resolveDrillConfig(type, requestedConfig = {}) {// Progressive cognitive ladders (default ON) — per-skill difficulty rungs// (n-back n/stimulusMs, digit-span span/direction, schulte grid, mental-- // rotation/stroop trial count). Selects the rung by sustained-accuracy- // mastery so the drill ramps up; when off, the caller's manual knobs+ // rotation transformation/options, Stroop interference mix). Selects the+ // rung by exact-level completion + accuracy, with speed gates where latency+ // is part of the skill; when off, the caller's manual knobs// (incl. stimulusMs/showMs) pass through unchanged. reaction-time has no// ladder and always passes through (issue #2095).if (cognitiveLadder(type)) {diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.jsindex 5cfd967cb1..4f02fbe2eb 100644--- a/server/services/meatspacePost.test.js+++ b/server/services/meatspacePost.test.js@@ -1941,6 +1941,53 @@ describe('progressive cognitive drills', () => {mockSessions([lowCompletion(0), lowCompletion(0), lowCompletion(0)]);const { progression } = await resolveDrillConfig('digit-span', {});expect(progression.level).toBe(0);+ expect(progression.levels[0]).toMatchObject({ attempts: 3, samples: 0, incompleteSamples: 3, completion: 0.25 });+ });++ it('keeps fully unanswered timed-out runs visible as excluded attempts', async () => {+ const timedOut = {+ date: today,+ tasks: [{+ module: 'cognitive',+ type: 'stroop',+ config: { level: 0 },+ accuracy: null,+ completion: 0,+ totalCount: 10,+ questions: Array.from({ length: 10 }, (_, index) => ({ index, answered: null, responseMs: 0 })),+ }],+ };+ mockSessions([timedOut, timedOut, timedOut]);++ const { progression } = await resolveDrillConfig('stroop', {});+ expect(progression.level).toBe(0);+ expect(progression.levels[0]).toMatchObject({ attempts: 3, samples: 0, incompleteSamples: 3, completion: 0 });+ });++ it('speed-gated cognitive rungs require enough fast exact-rung runs', async () => {+ const timedSession = (avgResponseMs) => ({+ date: today,+ tasks: [{+ module: 'cognitive',+ type: 'stroop',+ config: { level: 0 },+ accuracy: 0.95,+ completion: 1,+ avgResponseMs,+ totalCount: 10,+ questions: Array.from({ length: 10 }, (_, index) => ({ index, answered: 'blue', responseMs: avgResponseMs })),+ }],+ });++ mockSessions([timedSession(1700), timedSession(1700), timedSession(1700)]);+ const slow = await resolveDrillConfig('stroop', {});+ expect(slow.progression.level).toBe(0);+ expect(slow.progression.decision).toMatchObject({ action: 'hold', reasons: ['speed'] });++ mockSessions([timedSession(1000), timedSession(1100), timedSession(1200)]);+ const fast = await resolveDrillConfig('stroop', {});+ expect(fast.progression.level).toBe(1);+ expect(fast.config).toMatchObject({ incongruentPct: 65, count: 12 });});it('does not advance when accuracy is below the mastery bar', async () => {@@ -1979,6 +2026,13 @@ describe('progressive cognitive drills', () => {expect(config).toEqual({ mode: 'choice' });});+ it('mental-rotation progression stamps transformation and visual-complexity knobs', async () => {+ mockSessions([]);+ const { config, progression } = await resolveDrillConfig('mental-rotation', {});+ expect(progression.label).toContain('90°');+ expect(config).toMatchObject({ level: 0, rotationComplexity: 1, optionCount: 2 });+ });+it('generateDrill stamps the resolved level into the generated cognitive config', async () => {mockSessions([]);const { config } = await resolveDrillConfig('n-back', { length: 12 });diff --git a/server/services/meatspacePostCognitive.js b/server/services/meatspacePostCognitive.jsindex 7c534ce380..289ac22713 100644--- a/server/services/meatspacePostCognitive.js+++ b/server/services/meatspacePostCognitive.js@@ -77,8 +77,9 @@ function accuracySpeedScore(recomputed, refMs) {* is no data to derive them from, so downstream readers/aggregators stay safe.** NOTE: this treats `answered == null` as "not reached". It is therefore the- * right helper for skip-means-blank drills (stroop, schulte, mental-rotation,- * digit-span, reaction-time) but NOT for n-back, where withholding a press is a+ * right helper for skip-means-blank drills (Stroop, mental rotation, digit span,+ * reaction time) but NOT for Schulte (event stream) or n-back (go/no-go). In+ * n-back, withholding a press is a* deliberate "no-match" answer — n-back computes its own signal-detection metrics.*/export function answeredMetrics(recomputed) {@@ -238,17 +239,24 @@ export function generateDigitSpan(config = {}) {}/**- * Stroop trials. ~25% congruent (word matches ink), the rest incongruent. The- * correct answer is always the INK color.+ * Stroop trials with an exact configured conflict mix. Congruent trials have a+ * matching word and ink; incongruent trials deliberately disagree. The correct+ * answer is always the INK color.*/export function generateStroop(config = {}) {const count = clampInt(config.count, 5, 40, 15);+ const incongruentPct = clampInt(config.incongruentPct, 0, 100, 75);+ const incongruentCount = Math.round(count * incongruentPct / 100);+ const conflictFlags = shuffle([+ ...Array.from({ length: incongruentCount }, () => true),+ ...Array.from({ length: count - incongruentCount }, () => false),+ ]);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));+ const inkColor = conflictFlags[i]+ ? pick(STROOP_COLORS.filter(c => c.name !== wordColor.name))+ : wordColor;trials.push({word: wordColor.name,inkColor: inkColor.name,@@ -258,7 +266,7 @@ export function generateStroop(config = {}) {}return {type: 'stroop',- config: { count },+ config: { count, incongruentPct },trials,options: STROOP_COLORS.map(c => ({ name: c.name, hex: c.hex })),};@@ -283,25 +291,28 @@ export function generateSchulteTable(config = {}) {/*** Mental rotation: each trial shows a reference shape (an asymmetric- * grid-cell footprint) and 4 candidate shapes — exactly one is the reference+ * grid-cell footprint) and 2-4 candidate shapes — exactly one is the reference* rotated (0/90/180/270deg); the rest are mirrored (reflected) at a random* rotation, so they share a silhouette "feel" without being a true rotation- * match. `correctIndex` is the answer key; scoring recomputes it independently- * from `shape`/`rotationSteps`, never trusting the stored index round-trip.+ * match. The stored `correctIndex` supports immediate client feedback; server+ * scoring independently derives the answer from `shape`/`rotationSteps` and+ * the generated options.*/export function generateMentalRotation(config = {}) {const count = clampInt(config.count, 4, 20, 8);+ const rotationComplexity = clampInt(config.rotationComplexity, 1, 3, 3);+ const optionCount = clampInt(config.optionCount, 2, 4, 4);const shapeKeys = Object.keys(ROTATION_SHAPES);const trials = [];for (let i = 0; i < count; i++) {const shapeKey = pick(shapeKeys);const baseCells = ROTATION_SHAPES[shapeKey];- const rotationSteps = 1 + Math.floor(Math.random() * 3); // 1-3 (nonzero: 90/180/270deg)+ const rotationSteps = 1 + Math.floor(Math.random() * rotationComplexity);const correctCells = rotateCells(baseCells, rotationSteps);const options = [{ cells: correctCells, isMatch: true }];let guard = 0;- while (options.length < 4 && guard < 50) {+ while (options.length < optionCount && guard < 50) {guard++;const mirrored = mirrorCells(rotateCells(baseCells, Math.floor(Math.random() * 4)));const key = cellsKey(mirrored);@@ -313,12 +324,13 @@ export function generateMentalRotation(config = {}) {trials.push({shape: shapeKey,+ rotationSteps,target: normalizeCells(baseCells),options: shuffled.map(o => o.cells),correctIndex,});}- return { type: 'mental-rotation', config: { count, gridSize: 4 }, trials };+ return { type: 'mental-rotation', config: { count, gridSize: 4, rotationComplexity, optionCount }, trials };}/**@@ -510,27 +522,61 @@ function scoreStroop(drillData, questions) {return { score: accuracySpeedScore(recomputed, refMs), questions: recomputed, ...answeredMetrics(recomputed) };}-// Schulte table: each question is one "find the next number" step, keyed by-// `index` (0-based position in the 1..N sequence). Reference response window-// scales with grid size — a bigger grid needs more scanning per step.+// Schulte table: questions are the COMPLETE ordered click event stream. The+// server owns `currentTarget` and advances it only after a valid matching click;+// client-supplied index/expected/correct fields are ignored. That preserves+// wrong taps and repeated inputs as performance evidence instead of reconstructing+// an impossible perfect run from only successful targets.function scoreSchulteTable(drillData, questions) {const size = drillData?.config?.size || 5;- const total = size * size;- const refMs = 1000 + size * 500;- const recomputed = questions.map(q => {- const i = Number.isInteger(q.index) ? q.index : -1;- const expected = i + 1;- const answered = q.answered == null ? null : Number(q.answered);- return {- prompt: `${expected}`,- index: i,- expected,+ const generatedCells = Array.isArray(drillData?.cells)+ ? drillData.cells.filter(value => Number.isInteger(value) && value > 0)+ : [];+ const total = generatedCells.length || size * size;+ const tableValues = new Set(generatedCells.length+ ? generatedCells+ : Array.from({ length: total }, (_, i) => i + 1));+ const refMs = 1000 + Math.round(Math.sqrt(total)) * 500;+ const recomputed = [];+ let currentTarget = 1;+ for (const event of questions) {+ if (currentTarget > total) break;+ const selected = event?.answered == null ? null : Number(event.answered);+ const answered = Number.isInteger(selected) && tableValues.has(selected) ? selected : null;+ const correct = answered === currentTarget;+ recomputed.push({+ prompt: `${currentTarget}`,+ index: currentTarget - 1,+ expected: currentTarget,answered,- correct: i >= 0 && i < total && answered === expected,- responseMs: clampMs(q.responseMs, refMs),- };- });- return { score: accuracySpeedScore(recomputed, refMs), questions: recomputed, ...answeredMetrics(recomputed) };+ correct,+ responseMs: clampMs(event?.responseMs, refMs),+ });+ if (correct) currentTarget += 1;+ }++ const correctEvents = recomputed.filter(event => event.correct);+ const attemptCount = recomputed.length;+ const answeredCount = correctEvents.length;+ const errorCount = attemptCount - answeredCount;+ const accuracy = attemptCount ? answeredCount / attemptCount : null;+ const completion = total ? answeredCount / total : null;+ const avgResponseMs = answeredCount+ ? Math.round(correctEvents.reduce((sum, event) => sum + event.responseMs, 0) / answeredCount)+ : null;+ const speedBonus = avgResponseMs == null ? 0 : Math.max(0, 1 - avgResponseMs / refMs);+ const score = Math.round(((accuracy || 0) * 0.8 + speedBonus * 0.2) * (completion || 0) * 100);+ return {+ score,+ questions: recomputed,+ accuracy,+ completion,+ avgResponseMs,+ answeredCount,+ totalCount: total,+ attemptCount,+ errorCount,+ };}// Mental rotation: `index` selects the trial; `answered` is the option index@@ -541,7 +587,16 @@ function scoreMentalRotation(drillData, questions) {const refMs = 6000;const recomputed = questions.map(q => {const trial = trials[q.index] || {};- const expected = Number.isInteger(trial.correctIndex) ? trial.correctIndex : null;+ const baseCells = ROTATION_SHAPES[trial.shape];+ const generatedExpected = baseCells && Number.isInteger(trial.rotationSteps) && Array.isArray(trial.options)+ ? trial.options.findIndex(cells => cellsKey(normalizeCells(cells)) === cellsKey(rotateCells(baseCells, trial.rotationSteps)))+ : -1;+ // Legacy generated drills predate rotationSteps, so retain their stored+ // answer-key fallback. New drills recompute from shape + transformation ++ // options and never trust correctIndex.+ const expected = generatedExpected >= 0+ ? generatedExpected+ : Number.isInteger(trial.correctIndex) ? trial.correctIndex : null;const answered = q.answered == null ? null : Number(q.answered);return {prompt: q.prompt ?? `shape ${trial.shape ?? ''}`,diff --git a/server/services/meatspacePostCognitive.test.js b/server/services/meatspacePostCognitive.test.jsindex 6ebfba9b13..73e349c5c7 100644--- a/server/services/meatspacePostCognitive.test.js+++ b/server/services/meatspacePostCognitive.test.js@@ -58,7 +58,7 @@ describe('cognitive drill generators', () => {});it('stroop produces the requested trial count with a valid ink answer', () => {- const drill = generateStroop({ count: 12 });+ const drill = generateStroop({ count: 12, incongruentPct: 75 });expect(drill.type).toBe('stroop');expect(drill.trials).toHaveLength(12);const names = STROOP_COLORS.map(c => c.name);@@ -67,6 +67,8 @@ describe('cognitive drill generators', () => {expect(names).toContain(t.inkColor);expect(t.congruent).toBe(t.word === t.inkColor);}+ expect(drill.trials.filter(t => !t.congruent)).toHaveLength(9);+ expect(drill.config.incongruentPct).toBe(75);expect(drill.options.map(o => o.name).sort()).toEqual([...names].sort());});@@ -114,6 +116,18 @@ describe('cognitive drill generators', () => {}});+ it('mental-rotation applies transformation range and option-count difficulty', () => {+ const introductory = generateMentalRotation({ count: 6, rotationComplexity: 1, optionCount: 2 });+ expect(introductory.config).toMatchObject({ rotationComplexity: 1, optionCount: 2 });+ expect(introductory.trials.every(trial => trial.rotationSteps === 1)).toBe(true);+ expect(introductory.trials.every(trial => trial.options.length === 2)).toBe(true);++ const advanced = generateMentalRotation({ count: 6, rotationComplexity: 3, optionCount: 4 });+ expect(advanced.config).toMatchObject({ rotationComplexity: 3, optionCount: 4 });+ expect(advanced.trials.every(trial => trial.rotationSteps >= 1 && trial.rotationSteps <= 3)).toBe(true);+ expect(advanced.trials.every(trial => trial.options.length === 4)).toBe(true);+ });+it('ROTATION_SHAPES chirality invariant: every rotation is distinct, every mirrored-rotation is distinct, and no rotation ever equals a mirrored-rotation', () => {// This is the invariant generateMentalRotation's distractor-fill loop relies// on: without it, a base shape could silently yield fewer than 3 distinct@@ -310,6 +324,40 @@ describe('cognitive drill scorers (recompute the answer key, never trust client)expect(score).toBeLessThan(100);});+ it('schulte-table preserves wrong taps in order and cannot score a completed error run as perfect', () => {+ const drillData = { type: 'schulte-table', config: { size: 2 }, cells: [3, 1, 4, 2] };+ const result = scoreCognitiveDrill('schulte-table', drillData, [+ { index: 99, expected: 99, answered: 1, correct: false, responseMs: 400 },+ { index: 99, expected: 99, answered: 4, correct: true, responseMs: 200 }, // wrong; target stays 2+ { index: 0, expected: 1, answered: 2, correct: true, responseMs: 700 },+ { answered: 3, correct: true, responseMs: 500 },+ { answered: 4, correct: true, responseMs: 450 },+ ]);+ expect(result.questions.map(q => [q.expected, q.answered, q.correct])).toEqual([+ [1, 1, true],+ [2, 4, false],+ [2, 2, true],+ [3, 3, true],+ [4, 4, true],+ ]);+ expect(result).toMatchObject({ completion: 1, accuracy: 0.8, errorCount: 1, attemptCount: 5 });+ expect(result.score).toBeLessThan(100);+ });++ it('schulte-table repeated wrong inputs stay errors and incomplete runs stay incomplete', () => {+ const drillData = { type: 'schulte-table', config: { size: 3 }, cells: [1, 2, 3, 4, 5, 6, 7, 8, 9] };+ const result = scoreCognitiveDrill('schulte-table', drillData, [+ { answered: 2, responseMs: 100 },+ { answered: 2, responseMs: 200 },+ { answered: 1, responseMs: 300 },+ { answered: 2, responseMs: 400 },+ ]);+ expect(result.questions.map(q => q.expected)).toEqual([1, 1, 1, 2]);+ expect(result.errorCount).toBe(2);+ expect(result.answeredCount).toBe(2);+ expect(result.completion).toBeCloseTo(2 / 9);+ });+it('mental-rotation recomputes the answer from trials[index].correctIndex, not client claims', () => {const drillData = {type: 'mental-rotation',@@ -326,6 +374,20 @@ describe('cognitive drill scorers (recompute the answer key, never trust client)expect(questions[1].correct).toBe(false);});+ it('mental-rotation recomputes new drill answers from shape + rotation, not stored correctIndex', () => {+ const base = ROTATION_SHAPES.L;+ const correct = rotateCells(base, 1);+ const distractor = mirrorCells(base);+ const drillData = {+ type: 'mental-rotation',+ trials: [{ shape: 'L', rotationSteps: 1, correctIndex: 1, options: [correct, distractor] }],+ };+ const result = scoreCognitiveDrill('mental-rotation', drillData, [+ { index: 0, answered: 0, correct: false, responseMs: 3000 },+ ]);+ expect(result.questions[0]).toMatchObject({ expected: 0, answered: 0, correct: true });+ });+it('reaction-time simple mode marks a false start wrong even with a fast responseMs', () => {const drillData = { type: 'reaction-time', config: { mode: 'simple' }, trials: [{ delayMs: 1000 }, { delayMs: 1000 }] };const { questions, score, medianMs, bestMs } = scoreCognitiveDrill('reaction-time', drillData, [diff --git a/server/services/meatspacePostProgress.test.js b/server/services/meatspacePostProgress.test.jsindex 5cf5cb8ae2..65da67fe4f 100644--- a/server/services/meatspacePostProgress.test.js+++ b/server/services/meatspacePostProgress.test.js@@ -133,13 +133,34 @@ describe('getPostProgress bucketing', () => {expect(p.series.byDrill['multiplication'][0].date).toBe(d);});- it('includes a mastery block with the multiplication ladder and memory items', async () => {+ it('includes multiplication, cognitive evidence, and memory items in the mastery block', async () => {state.memoryItems = [{ id: 'm1', title: 'Elements', mastery: { overallPct: 42 }, schedule: { nextReview: '2000-01-01T00:00:00.000Z' } },];+ const schulteTask = () => ({+ module: 'cognitive',+ type: 'schulte-table',+ config: { level: 0 },+ score: 90,+ accuracy: 0.95,+ completion: 1,+ avgResponseMs: 2000,+ totalCount: 16,+ questions: [{ prompt: '1', answered: 1, correct: true, responseMs: 2000 }],+ });+ state.sessions = [{ date: todayStr(), durationMs: 60000, score: 90, tasks: [schulteTask(), schulteTask(), schulteTask()] }];const p = await getPostProgress({ days: 90 });expect(p.mastery.multiplication).toHaveProperty('level');expect(p.mastery.multiplication).toHaveProperty('floorLevel');+ expect(p.mastery.cognitive['schulte-table'].level).toBe(1);+ expect(p.mastery.cognitive['schulte-table'].levels[0]).toMatchObject({+ samples: 3,+ timedSamples: 3,+ completion: 1,+ targetMs: 2500,+ mastered: true,+ });+ expect(p.mastery.cognitive['schulte-table'].levels[0].accuracy).toBeCloseTo(0.95);// The memory service prepends a built-in item, so find ours by id.const mine = p.mastery.memoryItems.find(i => i.id === 'm1');expect(mine).toMatchObject({ id: 'm1', title: 'Elements', overallPct: 42 });