Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-2095]): per-skill progression ladders for cognitive drills
Adam Eivy30f0fdd1b5e7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e4bdf09513..dab3f71db6 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -25,6 +25,7 @@## POST Training+- **[issue-2095] Cognitive drills now level up as you master them, instead of training at one fixed difficulty forever.** N-back, digit span, Schulte table, mental rotation, and Stroop each climb their own mastery-gated ladder: n-back ramps 1-back → 2-back → 3-back and then squeezes the flash speed (2500 → 2000 → 1600ms); digit span grows its span and adds backward recall; Schulte grows the grid 4×4 → 6×6; mental rotation and Stroop add trials. You advance a rung only after sustained high accuracy at the current one (n-back uses the fair signal-detection accuracy, so never-pressing can't bank a level), and you're never demoted below a rung you've earned. Each drill now stamps its difficulty into your saved results, so progress is tracked per level (a 2-back run no longer pools with a 3-back run). The config page shows each drill's current rung and progress toward the next, with a per-drill "Progressive" toggle (on by default) — turn it off to set the knobs by hand, including the previously-hidden n-back stimulus speed and digit-span show time. Reaction time stays a fixed measurement. On by default for existing installs with no migration.- **[issue-2092] Morse progress now lives on the server, with WPM/accuracy trends and a per-character confusion matrix.** Your Koch level and every completed drill round are now saved server-side instead of only in the browser — so clearing browser data or switching devices (over Tailscale) no longer wipes your Morse mastery, and your level is identical everywhere. The first time you open the trainer it adopts your existing browser level once, then keeps both in sync. A new **Morse Progress** panel on `/post/morse` charts accuracy and effective-WPM trends per mode (Copy / Head Copy / Send), highlights your most-confused character pairs (E↔I and friends), and lists your weakest characters worst-first so you know exactly which to drill next. Send-mode rounds record per-character keying accuracy and timing too.## Roundsdiff --git a/client/src/components/meatspace/post/PostDrillConfig.jsx b/client/src/components/meatspace/post/PostDrillConfig.jsxindex 2c3bee0716..499b3f8eb2 100644--- a/client/src/components/meatspace/post/PostDrillConfig.jsx+++ b/client/src/components/meatspace/post/PostDrillConfig.jsx@@ -1,6 +1,6 @@import { useState, useEffect } from 'react';import { ArrowLeft, Save, Brain, Bell, TrendingUp, TrendingDown, Minus } from 'lucide-react';-import { updatePostConfig, getProviders, getPostAdaptivePreview, getPostMultiplicationProgress } from '../../../services/api';+import { updatePostConfig, getProviders, getPostAdaptivePreview, getPostMultiplicationProgress, getPostCognitiveProgress } from '../../../services/api';import toast from '../../ui/Toast';import { FormField } from '../../ui/FormField';import { filterSelectableModels, enabledApiProviderFilter } from '../../../utils/providers';@@ -156,15 +156,21 @@ const COGNITIVE_DRILL_META = {'n-back': {label: 'N-Back',desc: 'Signal when a letter matches the one N steps back — working memory',+ // `progressive: true` marks a laddered drill — the ProgressiveBadge + toggle+ // render, and every listed field is ladder-managed (hidden while progressive+ // is on; shown, incl. stimulusMs, in manual mode). See server/lib/postProgression.js.+ progressive: true,fields: [{ key: 'n', label: 'N (steps back)', type: 'number', min: 1, max: 3 },{ key: 'length', label: 'Sequence Length', type: 'number', min: 6, max: 60 },+ { key: 'stimulusMs', label: 'Stimulus (ms)', type: 'number', min: 1000, max: 5000 },],- defaults: { enabled: true, n: 2, length: 20 },+ defaults: { enabled: true, progressive: true, n: 2, length: 20, stimulusMs: 2500 },},'digit-span': {label: 'Digit Span',desc: 'Recall a shown digit sequence forward or backward',+ progressive: true,fields: [{ key: 'direction', label: 'Direction', type: 'select', options: [{ value: 'forward', label: 'Forward' },@@ -172,32 +178,36 @@ const COGNITIVE_DRILL_META = {] },{ key: 'startLength', label: 'Start Length', type: 'number', min: 3, max: 9 },{ key: 'maxLength', label: 'Max Length', type: 'number', min: 3, max: 12 },+ { key: 'showMs', label: 'Show Time (ms)', type: 'number', min: 400, max: 4000 },],- defaults: { enabled: true, direction: 'forward', startLength: 3, maxLength: 8 },+ defaults: { enabled: true, progressive: true, direction: 'forward', startLength: 3, maxLength: 8, showMs: 1000 },},'stroop': {label: 'Stroop',desc: 'Name the ink color of a color-word — attention & inhibition',+ progressive: true,fields: [{ key: 'count', label: 'Trials', type: 'number', min: 5, max: 40 },],- defaults: { enabled: true, count: 15 },+ defaults: { enabled: true, progressive: true, count: 15 },},'schulte-table': {label: 'Schulte Table',desc: 'Scan a shuffled grid and tap 1, 2, 3... in order — visual attention & speed',+ progressive: true,fields: [{ key: 'size', label: 'Grid Size (NxN)', type: 'number', min: 3, max: 7 },],- defaults: { enabled: true, size: 5 },+ defaults: { enabled: true, progressive: true, size: 5 },},'mental-rotation': {label: 'Mental Rotation',desc: 'Pick the shape that’s the same, just rotated — spatial reasoning',+ progressive: true,fields: [{ key: 'count', label: 'Trials', type: 'number', min: 4, max: 20 },],- defaults: { enabled: true, count: 8 },+ defaults: { enabled: true, progressive: true, count: 8 },},'reaction-time': {label: 'Reaction Time',@@ -317,9 +327,11 @@ function AdaptiveBadge({ info }) {);}-// Compact ladder status for progressive multiplication: current rung, mastery-// dots for every rung, and the speed/accuracy gate that unlocks the next one.-function ProgressiveBadge({ info }) {+// Compact ladder status for a progressive drill: current rung, mastery dots for+// every rung, and the accuracy (+ optional speed) gate that unlocks the next+// one. Shared by multiplication (speed-gated) and the cognitive ladders+// (accuracy-only); `managedLabel` names the manual knob(s) the ladder overrides.+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);return (@@ -343,7 +355,7 @@ function ProgressiveBadge({ info }) {))}</div><p className="text-xs text-gray-500">- Advances to the next rung after ≥{pct}% accuracy and fast responses at this one. Max Digits is ignored while progressive is on.+ 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.</p></div>);@@ -375,9 +387,13 @@ function GroupBulkToggle({ groupLabel, onEnableAll, onDisableAll }) {);}-function DrillCard({ meta, drillConfig, enabled, accent, onToggle, onUpdateField, adaptiveInfo, progressive, onToggleProgressive, progressInfo }) {+function DrillCard({ meta, drillConfig, enabled, accent, onToggle, onUpdateField, adaptiveInfo, progressive, onToggleProgressive, progressInfo, managedFieldKeys = [], speedGated = false, managedLabel = 'Manual knobs' }) {const supportsProgressive = typeof progressive === 'boolean';- const hideMaxDigits = supportsProgressive && progressive;+ // Fields the ladder drives (hidden while progressive is on; shown in manual+ // mode). Multiplication hides only Max Digits; a cognitive drill hides every+ // difficulty knob (incl. the newly-exposed stimulusMs/showMs).+ const managed = new Set(managedFieldKeys);+ const hideManaged = supportsProgressive && progressive;const activeBorder = accent === 'accent-2' ? 'border-port-accent-2/30' : 'border-port-border';const toggleBg = accent === 'accent-2' ? 'bg-port-accent-2' : 'bg-port-accent';return (@@ -415,7 +431,7 @@ function DrillCard({ meta, drillConfig, enabled, accent, onToggle, onUpdateFieldtype="button"role="switch"aria-checked={progressive}- aria-label="Progressive difficulty"+ aria-label={`Progressive difficulty — ${meta.label}`}onClick={onToggleProgressive}className={`shrink-0 w-10 h-5 rounded-full transition-colors relative ${progressive ? toggleBg : 'bg-port-border'@@ -430,7 +446,7 @@ function DrillCard({ meta, drillConfig, enabled, accent, onToggle, onUpdateField{enabled && (<div className="grid grid-cols-2 gap-3">- {meta.fields.filter(field => !(hideMaxDigits && field.key === 'maxDigits')).map(field => (+ {meta.fields.filter(field => !(hideManaged && managed.has(field.key))).map(field => (<FormField key={field.key} label={field.label} labelClassName="text-xs text-gray-500 mb-1 block">{field.type === 'select' ? (<select@@ -457,7 +473,7 @@ function DrillCard({ meta, drillConfig, enabled, accent, onToggle, onUpdateField</div>)}- {enabled && supportsProgressive && progressive && <ProgressiveBadge info={progressInfo} />}+ {enabled && supportsProgressive && progressive && <ProgressiveBadge info={progressInfo} speedGated={speedGated} managedLabel={managedLabel} />}{enabled && !(supportsProgressive && progressive) && <AdaptiveBadge info={adaptiveInfo} />}</div>);@@ -490,6 +506,7 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {);const [adaptivePreview, setAdaptivePreview] = useState(null);const [multiplicationProgress, setMultiplicationProgress] = useState(null);+ const [cognitiveProgress, setCognitiveProgress] = useState(null);// Opt-in daily reminder — off by default; see server/services/meatspacePostReminder.js.const [reminderEnabled, setReminderEnabled] = useState(() => config?.reminder?.enabled === true@@ -530,6 +547,22 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {return () => { cancelled = true; };}, [multiplicationProgressive]);+ // Progressive cognitive-ladder status (per drill type), same pattern as the+ // multiplication badge. Fetched whenever the cognitive section is on and any+ // cognitive drill is progressive — the badge is a transparency aid, so the+ // saved server state (not the unsaved form) drives it.+ const anyCognitiveProgressive = cognitiveEnabled && COGNITIVE_TYPES.some(+ type => COGNITIVE_DRILL_META[type].progressive && cognitiveDrillTypes[type]?.progressive !== false+ );+ useEffect(() => {+ if (!anyCognitiveProgressive) { setCognitiveProgress(null); return; }+ let cancelled = false;+ getPostCognitiveProgress()+ .then(p => { if (!cancelled) setCognitiveProgress(p); })+ .catch(err => console.warn('⚠️ Failed to load cognitive progress: ' + err.message));+ return () => { cancelled = true; };+ }, [anyCognitiveProgressive]);+function toggleDrill(type) {setDrillTypes(prev => ({...prev,@@ -578,6 +611,13 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {}));}+ function toggleCognitiveProgressive(type) {+ setCognitiveDrillTypes(prev => ({+ ...prev,+ [type]: { ...prev[type], progressive: !(prev[type]?.progressive !== false) }+ }));+ }+function updateCognitiveField(type, key, value) {let coerced;if (COGNITIVE_STRING_FIELDS.has(key)) {@@ -790,6 +830,9 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {progressive={isMultiplication ? multiplicationProgressive : undefined}onToggleProgressive={isMultiplication ? toggleProgressive : undefined}progressInfo={isMultiplication ? multiplicationProgress : null}+ managedFieldKeys={isMultiplication ? ['maxDigits'] : []}+ speedGated={isMultiplication}+ managedLabel="Max Digits"/>);})}@@ -829,6 +872,11 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {<div className={CARD_GRID}>{Object.entries(COGNITIVE_DRILL_META).map(([type, meta]) => {const drillConfig = cognitiveDrillTypes[type] || {};+ // Laddered cognitive drills expose a Progressive toggle + rung badge+ // (reaction-time has no ladder). When on, every difficulty knob is+ // ladder-managed and hidden (issue #2095).+ const supportsProgressive = meta.progressive === true;+ const progressive = supportsProgressive ? drillConfig.progressive !== false : undefined;return (<DrillCardkey={type}@@ -838,6 +886,12 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {accent="accent"onToggle={() => toggleCognitiveDrill(type)}onUpdateField={(key, value) => updateCognitiveField(type, key, value)}+ progressive={progressive}+ onToggleProgressive={supportsProgressive ? () => toggleCognitiveProgressive(type) : undefined}+ progressInfo={supportsProgressive ? cognitiveProgress?.[type] : null}+ managedFieldKeys={supportsProgressive ? meta.fields.map(f => f.key) : []}+ speedGated={false}+ managedLabel="Manual knobs"/>);})}diff --git a/client/src/components/meatspace/post/PostDrillConfig.test.jsx b/client/src/components/meatspace/post/PostDrillConfig.test.jsxindex 37ee9e5009..a7c81dc09f 100644--- a/client/src/components/meatspace/post/PostDrillConfig.test.jsx+++ b/client/src/components/meatspace/post/PostDrillConfig.test.jsx@@ -6,11 +6,12 @@ vi.mock('../../../services/api', () => ({getProviders: vi.fn(),getPostAdaptivePreview: vi.fn(),getPostMultiplicationProgress: vi.fn(),+ getPostCognitiveProgress: vi.fn(),}));vi.mock('../../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));import PostDrillConfig from './PostDrillConfig';-import { updatePostConfig, getProviders, getPostAdaptivePreview, getPostMultiplicationProgress } from '../../../services/api';+import { updatePostConfig, getProviders, getPostAdaptivePreview, getPostMultiplicationProgress, getPostCognitiveProgress } from '../../../services/api';// The 14 generatable LLM drill types (mirror server + client constants).const ALL_LLM_TYPES = [@@ -63,6 +64,17 @@ beforeEach(() => {thresholds: { minSamples: 12, targetAccuracy: 0.9 },windowDays: 30,});+ getPostCognitiveProgress.mockResolvedValue({+ 'n-back': {+ 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: 2, label: '3-back @ 2500ms', mastered: false },+ ],+ thresholds: { minSamples: 3, targetAccuracy: 0.85 }, windowDays: 30,+ },+ });});describe('PostDrillConfig', () => {@@ -191,7 +203,7 @@ describe('PostDrillConfig', () => {it('multiplication defaults to Progressive difficulty on, hiding Max Digits and showing the ladder', async () => {render(<PostDrillConfig config={config} onSaved={vi.fn()} onBack={vi.fn()} />);- const toggle = screen.getByRole('switch', { name: 'Progressive difficulty' });+ const toggle = screen.getByRole('switch', { name: 'Progressive difficulty — Multiplication' });expect(toggle.getAttribute('aria-checked')).toBe('true');// Max Digits is ignored while progressive is on, so its field is hidden.expect(screen.queryByText('Max Digits')).toBeNull();@@ -202,13 +214,32 @@ describe('PostDrillConfig', () => {it('toggling Progressive off reveals Max Digits and persists progressive=false', async () => {render(<PostDrillConfig config={config} onSaved={vi.fn()} onBack={vi.fn()} />);- fireEvent.click(screen.getByRole('switch', { name: 'Progressive difficulty' }));+ fireEvent.click(screen.getByRole('switch', { name: 'Progressive difficulty — Multiplication' }));expect(screen.getByText('Max Digits')).toBeTruthy();fireEvent.click(screen.getByText('Save'));await waitFor(() => expect(updatePostConfig).toHaveBeenCalled());expect(updatePostConfig.mock.calls[0][0].mentalMath.drillTypes.multiplication.progressive).toBe(false);});+ it('cognitive drills default to Progressive on — n-back hides its knobs and shows its rung', async () => {+ render(<PostDrillConfig config={config} onSaved={vi.fn()} onBack={vi.fn()} />);+ const toggle = screen.getByRole('switch', { name: 'Progressive difficulty — N-Back' });+ expect(toggle.getAttribute('aria-checked')).toBe('true');+ // Progressive on → the ladder-managed knobs (incl. Stimulus) are hidden.+ expect(screen.queryByText('Stimulus (ms)')).toBeNull();+ await waitFor(() => expect(getPostCognitiveProgress).toHaveBeenCalled());+ await waitFor(() => expect(screen.getByText(/Level 2 of 3 · 2-back @ 2500ms/)).toBeTruthy());+ });++ it('turning n-back Progressive off exposes the Stimulus (ms) knob and persists progressive=false', async () => {+ render(<PostDrillConfig config={config} onSaved={vi.fn()} onBack={vi.fn()} />);+ fireEvent.click(screen.getByRole('switch', { name: 'Progressive difficulty — N-Back' }));+ expect(screen.getByText('Stimulus (ms)')).toBeTruthy();+ fireEvent.click(screen.getByText('Save'));+ await waitFor(() => expect(updatePostConfig).toHaveBeenCalled());+ expect(updatePostConfig.mock.calls[0][0].cognitive.drillTypes['n-back'].progressive).toBe(false);+ });+it('toggling Adaptive on persists enabled=true', async () => {render(<PostDrillConfig config={config} onSaved={vi.fn()} onBack={vi.fn()} />);fireEvent.click(screen.getByRole('switch', { name: 'Adaptive difficulty' }));diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.jsindex bc1f119c5e..149afea6b6 100644--- a/client/src/services/apiMeatspace.js+++ b/client/src/services/apiMeatspace.js@@ -188,6 +188,7 @@ export const submitPostSession = (data, options = {}) => request('/meatspace/posexport const getPostStats = (days) => request(`/meatspace/post/stats${days != null ? `?days=${days}` : ''}`);export const getPostAdaptivePreview = () => request('/meatspace/post/adaptive-preview');export const getPostMultiplicationProgress = () => request('/meatspace/post/multiplication-progress');+export const getPostCognitiveProgress = () => request('/meatspace/post/cognitive-progress');export const generatePostDrill = (type, config = {}, providerId, model, options = {}) => request('/meatspace/post/drill', {method: 'POST',body: JSON.stringify({ type, config, ...(providerId && { providerId }), ...(model && { model }) }),diff --git a/server/lib/README.md b/server/lib/README.mdindex ec50842515..5f63f8090c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -214,7 +214,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `textUtils.js` | Pure server-side prose helpers. `countWords(text)` — canonical whitespace-token count (`\S+`), the single home for what `writersRoom/local.js`, `issueLength.js`, and the client's `formatters.js` used to each re-implement. || `pipelineIssueOrder.js` | Pure renumber algorithm for pipeline issues. || `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. |+| `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`. |+| `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. || `planIds.js` | Utilities for PLAN.md `[slug]` IDs. || `renderSlot.js` | Render-slot helpers for `(proof\|final)Image` per stage. || `telegramClient.js` | Telegram bot client. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 76e9ba10af..9362a65ce8 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -190,6 +190,7 @@ export * from './personaTraitBlend.js';export * from './pipelineIssueOrder.js';export * from './postAdaptive.js';export * from './postMultiplicationLadder.js';+export * from './postProgression.js';export * from './planIds.js';export * from './renderSlot.js';export * from './telegramClient.js';diff --git a/server/lib/postMultiplicationLadder.js b/server/lib/postMultiplicationLadder.jsindex c241378871..cb0197ba5b 100644--- a/server/lib/postMultiplicationLadder.js+++ b/server/lib/postMultiplicationLadder.js@@ -18,8 +18,15 @@* Progression is derived from scored session history: each generated drill* stamps its `level` into the task config, so later we can bucket answered* questions by level and measure per-level accuracy + response time.+ *+ * The generic mastery/floor machinery lives in `postProgression.js` (shared+ * with the cognitive-drill ladders); this module is the multiplication-specific+ * ladder + the speed-target curve, wired onto that helper. Its public API is+ * unchanged — it is the reference ladder the shared helper was extracted from.*/+import { createProgression, PROGRESSION_MASTERY_DEFAULTS } from './postProgression.js';+// Ordered difficulty ladder. Each entry lists the digit-count of every factor// in a problem, so `[1, 2]` = single-digit × double-digit and `[1, 1, 1]` =// three single-digit factors. Rungs are hand-authored (not computed) so the@@ -58,11 +65,6 @@ export const MASTERY_DEFAULTS = {responseMsCap: 120000,};-export function clampMultiplicationLevel(level) {- const n = Number.isInteger(level) ? level : 0;- return Math.min(MAX_MULTIPLICATION_LEVEL, Math.max(0, n));-}-/*** The factor-digit spec for a ladder level (clamped into range).* @returns {number[]} e.g. [1, 2]@@ -78,14 +80,36 @@ export function describeMultiplicationLevel(level) {return `${ladderFactors(level).join('×')}-digit`;}+// Per-level response-time target (ms): scales with the total number of digits+// across all factors, floored at `minTargetMs`. This is the multiplication+// ladder's speed curve, handed to the shared helper so it can gate mastery on+// speed (fast AND accurate) rather than accuracy alone.+function multiplicationSpeedTarget(level, opts) {+ const options = { ...MASTERY_DEFAULTS, ...opts };+ const totalDigits = MULTIPLICATION_LADDER[level].reduce((a, b) => a + b, 0);+ return Math.max(options.minTargetMs, options.baseMsPerFactorDigit * totalDigits);+}++// Shared progression resolver for the multiplication ladder. `mastery` carries+// the extra `baseMsPerFactorDigit`/`minTargetMs` fields the speed curve reads;+// the generic helper ignores keys it doesn't use.+const progression = createProgression({+ levels: MULTIPLICATION_LADDER,+ describeLevel: describeMultiplicationLevel,+ mastery: { ...PROGRESSION_MASTERY_DEFAULTS, ...MASTERY_DEFAULTS },+ speedTargetForLevel: multiplicationSpeedTarget,+});++export function clampMultiplicationLevel(level) {+ return progression.clampLevel(level);+}+/*** Per-question response-time target (ms) for a level. Scales with the total* number of digits across all factors, floored at `minTargetMs`.*/export function speedTargetMs(level, opts = MASTERY_DEFAULTS) {- const options = { ...MASTERY_DEFAULTS, ...opts };- const totalDigits = ladderFactors(level).reduce((a, b) => a + b, 0);- return Math.max(options.minTargetMs, options.baseMsPerFactorDigit * totalDigits);+ return progression.speedTargetMs(level, opts);}/**@@ -94,15 +118,7 @@ export function speedTargetMs(level, opts = MASTERY_DEFAULTS) {* @param {{samples?: number, accuracy?: number, avgResponseMs?: number}} stat*/export function isLevelMastered(stat, level, opts = MASTERY_DEFAULTS) {- const options = { ...MASTERY_DEFAULTS, ...opts };- 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;- if (samples < options.minSamples) return false;- if (accuracy < options.targetAccuracy) return false;- // avgResponseMs of 0 means no timed samples — never treat as "instant mastery".- if (avgResponseMs <= 0) return false;- return avgResponseMs <= speedTargetMs(level, options);+ return progression.isLevelMastered(stat, level, opts);}/**@@ -118,9 +134,7 @@ export function isLevelMastered(stat, level, opts = MASTERY_DEFAULTS) {* windowed). It is the anti-demotion floor: because mastery is judged over a* rolling window, a rung's samples fall to 0 once its evidence ages out — but* you only ever reach a higher rung by having cleared the ones below it, so- * earned progress must not be lost when it ages out. Without this floor a user- * grinding level 3 would snap back to level 0 (`7 × 8`) the day their earliest- * level-0 sessions crossed the window cutoff.+ * earned progress must not be lost when it ages out.** @param {Record<number|string, {samples:number, accuracy:number, avgResponseMs:number}>} levelStats* @param {object} [opts] - override MASTERY_DEFAULTS thresholds@@ -128,48 +142,25 @@ export function isLevelMastered(stat, level, opts = MASTERY_DEFAULTS) {* @returns {{level, factors, label, atHardest, currentMastered, floorLevel, levels}}*/export function resolveMultiplicationLevel(levelStats = {}, opts = {}, floorLevel = 0) {- const options = { ...MASTERY_DEFAULTS, ...opts };- const floor = clampMultiplicationLevel(floorLevel);- const levels = MULTIPLICATION_LADDER.map((factors, level) => {- const stat = levelStats?.[level] || levelStats?.[String(level)] || {};- 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 targetMs = speedTargetMs(level, options);- return {- level,- factors,- label: describeMultiplicationLevel(level),- samples,- accuracy,- avgResponseMs,- targetMs,- mastered: isLevelMastered({ samples, accuracy, avgResponseMs }, level, options),- };- });-- // Advance from the earned floor while the current rung's recent performance- // clears the mastery bar. Starting at `floor` (not 0) prevents involuntary- // demotion of rungs whose window evidence has aged out.- let level = floor;- while (level < MAX_MULTIPLICATION_LEVEL && levels[level].mastered) level += 1;-- // For the UI: every rung strictly below the resolved level has been cleared- // (you can't be on rung N without having passed the ones beneath it), so mark- // it mastered even if its recent window is empty — otherwise the ladder dots- // would falsely show a cleared rung as un-mastered after it ages out.- for (const rung of levels) {- if (rung.level < level) rung.mastered = true;- }-- const current = levels[level];+ const res = progression.resolveLevel(levelStats, opts, floorLevel);return {- level,- factors: current.factors,- label: current.label,- atHardest: level >= MAX_MULTIPLICATION_LEVEL,- currentMastered: current.mastered,- floorLevel: floor,- levels,+ level: res.level,+ factors: MULTIPLICATION_LADDER[res.level],+ label: res.label,+ atHardest: res.atHardest,+ currentMastered: res.currentMastered,+ floorLevel: res.floorLevel,+ // Re-key each rung to the multiplication shape (`factors` from the generic+ // `descriptor`), preserving the exact fields the ladder always exposed.+ levels: res.levels.map(rung => ({+ level: rung.level,+ factors: rung.descriptor,+ label: rung.label,+ samples: rung.samples,+ accuracy: rung.accuracy,+ avgResponseMs: rung.avgResponseMs,+ targetMs: rung.targetMs,+ mastered: rung.mastered,+ })),};}diff --git a/server/lib/postProgression.js b/server/lib/postProgression.jsnew file mode 100644index 0000000000..26edf9dcbd--- /dev/null+++ b/server/lib/postProgression.js@@ -0,0 +1,299 @@+/**+ * Generic POST mastery-gated progression ladder (pure, side-effect-free).+ *+ * Extracted from `postMultiplicationLadder.js` so ANY drill — not just+ * multiplication — can declare an ordered level list plus a mastery predicate+ * and get level resolution (with an anti-demotion floor) for free.+ *+ * A ladder is an ordered array of opaque "rung descriptors" (for multiplication+ * a per-factor digit-count array; for a cognitive drill the generator-config+ * knobs at that difficulty). `createProgression` turns a ladder definition into+ * the same resolver shape the multiplication ladder always exposed:+ *+ * - `clampLevel(level)` — clamp into [0, maxLevel]+ * - `speedTargetMs(level, o)` — per-level response-time target (or null)+ * - `describeLevel(level)` — short human label+ * - `isLevelMastered(stat, l)` — samples + accuracy (+ optional speed) gate+ * - `resolveLevel(stats, o, f)` — walk up from the earned floor to the first+ * un-mastered rung; returns a UI explainer+ *+ * Mastery is judged over a rolling window, but a rung's earned progress must+ * survive its evidence aging out — that's the `floorLevel` (highest rung ever+ * reached, all-time). Without it a user grinding rung 3 would snap back to 0+ * the day their earliest rung-0 sessions crossed the window cutoff.+ *+ * A ladder that supplies `speedTargetForLevel` is *speed-gated* (mastery also+ * 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).+ */++// Shared mastery thresholds. Ladder definitions override any subset via+// `def.mastery`. `windowDays`/`responseMsCap` are consumed by the service that+// aggregates per-level stats, not by this pure module, but they live here so a+// ladder has one source of truth for its thresholds.+export const PROGRESSION_MASTERY_DEFAULTS = {+ // Answered samples accumulated at a level before it can be judged mastered.+ minSamples: 12,+ // Fraction of samples that must be correct (accuracy 0-1).+ targetAccuracy: 0.9,+ // Rolling window (days) the mastery signal is read over. Earned rungs never+ // age out below the floor (see resolveLevel).+ windowDays: 30,+ // Samples slower than this are clamped before averaging, so one walked-away+ // answer can't inflate a level's avgResponseMs and block mastery.+ responseMsCap: 120000,+};++export function clampLevel(level, maxLevel) {+ const n = Number.isInteger(level) ? level : 0;+ return Math.min(maxLevel, Math.max(0, n));+}++/**+ * Build a progression resolver from a ladder definition.+ *+ * @param {object} def+ * @param {any[]} def.levels - ordered rung descriptors (opaque to this module)+ * @param {(level:number)=>string} def.describeLevel - short label for a rung+ * @param {object} [def.mastery] - overrides for PROGRESSION_MASTERY_DEFAULTS+ * @param {(level:number, opts:object)=>number|null} [def.speedTargetForLevel] -+ * when it returns a positive finite ms target, mastery additionally requires+ * `avgResponseMs` in `(0, target]`; when null/undefined/absent, mastery is+ * accuracy-only.+ */+export function createProgression(def) {+ const levels = def.levels;+ const maxLevel = levels.length - 1;+ const masteryDefaults = { ...PROGRESSION_MASTERY_DEFAULTS, ...(def.mastery || {}) };+ const speedTargetForLevel = typeof def.speedTargetForLevel === 'function' ? def.speedTargetForLevel : null;++ const clamp = level => clampLevel(level, maxLevel);+ const describeLevel = level => def.describeLevel(clamp(level));++ const speedTargetMs = (level, opts = masteryDefaults) => {+ if (!speedTargetForLevel) return null;+ return speedTargetForLevel(clamp(level), { ...masteryDefaults, ...opts });+ };++ const isLevelMastered = (stat, level, opts = masteryDefaults) => {+ const options = { ...masteryDefaults, ...opts };+ 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;+ 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 (avgResponseMs <= 0) return false;+ return avgResponseMs <= target;+ }+ return true;+ };++ /**+ * Resolve the current level from per-level performance stats. Walks up from+ * the earned `floorLevel` and stops at the first un-mastered rung. Returns a+ * transparent explainer with every rung's status so the UI can render the+ * ladder.+ */+ const resolveLevel = (levelStats = {}, opts = {}, floorLevel = 0) => {+ const options = { ...masteryDefaults, ...opts };+ const floor = clamp(floorLevel);+ const rungs = levels.map((descriptor, level) => {+ const stat = levelStats?.[level] || levelStats?.[String(level)] || {};+ 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 targetMs = speedTargetForLevel ? speedTargetForLevel(level, options) : null;+ return {+ level,+ descriptor,+ label: def.describeLevel(level),+ samples,+ accuracy,+ avgResponseMs,+ targetMs,+ mastered: isLevelMastered({ samples, accuracy, avgResponseMs }, level, options),+ };+ });++ // Advance from the earned floor while the current rung's recent performance+ // clears the bar. Starting at `floor` prevents involuntary demotion of+ // rungs whose window evidence has aged out.+ let level = floor;+ while (level < maxLevel && rungs[level].mastered) level += 1;++ // Every rung strictly below the resolved level has been cleared, so render+ // it mastered even if its recent window is empty.+ for (const rung of rungs) {+ if (rung.level < level) rung.mastered = true;+ }++ const current = rungs[level];+ return {+ level,+ label: current.label,+ atHardest: level >= maxLevel,+ currentMastered: current.mastered,+ floorLevel: floor,+ levels: rungs,+ };+ };++ return {+ levels,+ maxLevel,+ masteryDefaults,+ clampLevel: clamp,+ describeLevel,+ speedTargetMs,+ isLevelMastered,+ resolveLevel,+ };+}++// =============================================================================+// COGNITIVE DRILL LADDERS+// =============================================================================+//+// Each ladder is an ordered list of generator-config knob objects: rung N's+// object is spread into the drill's requested config at generation time (via+// meatspacePost.js resolveDrillConfig), so climbing the ladder literally makes+// the generated drill harder. `describe` turns a rung into a short label for+// 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 /+// signal-detection accuracy from #2094, so the do-nothing exploit can't bank a+// rung.++export const COGNITIVE_MASTERY_DEFAULTS = {+ // A "sample" here is one completed drill at a level (not one answered+ // question), so a handful of clean runs is enough to advance.+ minSamples: 3,+ targetAccuracy: 0.85,+ windowDays: 30,+};++export const COGNITIVE_LADDERS = {+ // Working memory: raise n first (1→2→3), then squeeze the presentation time+ // (2500→2000→1600ms) once 3-back is held — the two real difficulty levers.+ 'n-back': {+ levels: [+ { n: 1, stimulusMs: 2500 },+ { n: 2, stimulusMs: 2500 },+ { n: 3, stimulusMs: 2500 },+ { n: 3, stimulusMs: 2000 },+ { n: 3, stimulusMs: 1600 },+ ],+ describe: rung => `${rung.n}-back @ ${rung.stimulusMs}ms`,+ },+ // Working memory span: grow the length window (4→9), forward first, then the+ // harder backward recall.+ 'digit-span': {+ levels: [+ { direction: 'forward', startLength: 4, maxLength: 6 },+ { direction: 'forward', startLength: 5, maxLength: 7 },+ { direction: 'forward', startLength: 6, maxLength: 8 },+ { direction: 'backward', startLength: 4, maxLength: 6 },+ { direction: 'backward', startLength: 5, maxLength: 7 },+ { direction: 'backward', startLength: 6, maxLength: 9 },+ ],+ describe: rung => `${rung.direction} ${rung.startLength}–${rung.maxLength}`,+ },+ // Visual attention: bigger grid = more to scan (4×4 → 6×6).+ 'schulte-table': {+ levels: [+ { size: 4 },+ { size: 5 },+ { size: 6 },+ ],+ describe: rung => `${rung.size}×${rung.size}`,+ },+ // Spatial reasoning: more trials per run (time pressure via volume).+ 'mental-rotation': {+ levels: [+ { count: 6 },+ { count: 8 },+ { count: 10 },+ { count: 12 },+ ],+ describe: rung => `${rung.count} trials`,+ },+ // Attention/inhibition: more trials per run.+ 'stroop': {+ levels: [+ { count: 10 },+ { count: 15 },+ { count: 20 },+ { count: 25 },+ ],+ describe: rung => `${rung.count} trials`,+ },+};++// Laddered cognitive drill types (drives getCognitiveProgress + the config UI).+export const COGNITIVE_LADDER_TYPES = Object.keys(COGNITIVE_LADDERS);++// Memoized per-type progression resolvers (createProgression is cheap but the+// ladder shape is fixed, so build once).+const cognitiveProgressions = {};++export function cognitiveProgression(type) {+ const ladder = COGNITIVE_LADDERS[type];+ if (!ladder) return null;+ if (!cognitiveProgressions[type]) {+ cognitiveProgressions[type] = createProgression({+ levels: ladder.levels,+ describeLevel: level => ladder.describe(ladder.levels[level]),+ mastery: COGNITIVE_MASTERY_DEFAULTS,+ // No speedTargetForLevel → accuracy-only mastery.+ });+ }+ return cognitiveProgressions[type];+}++export function cognitiveLadder(type) {+ return COGNITIVE_LADDERS[type] || null;+}++/**+ * The generator-config knobs for a cognitive rung (clamped into range), spread+ * into the requested config at generation time. `{}` for a non-laddered type.+ */+export function cognitiveLevelConfig(type, level) {+ const prog = cognitiveProgression(type);+ if (!prog) return {};+ const idx = prog.clampLevel(level);+ return { ...COGNITIVE_LADDERS[type].levels[idx] };+}++/**+ * Resolve a cognitive drill's progressive difficulty from per-level stats.+ * Returns the generic resolveLevel explainer plus `type`, the resolved rung's+ * generator `config`, and the window/threshold metadata the badge shows.+ * `null` for a non-laddered type.+ */+export function resolveCognitiveProgression(type, levelStats = {}, floorLevel = 0) {+ const prog = cognitiveProgression(type);+ if (!prog) return null;+ const res = prog.resolveLevel(levelStats, {}, floorLevel);+ return {+ ...res,+ type,+ config: cognitiveLevelConfig(type, res.level),+ windowDays: COGNITIVE_MASTERY_DEFAULTS.windowDays,+ thresholds: {+ minSamples: COGNITIVE_MASTERY_DEFAULTS.minSamples,+ targetAccuracy: COGNITIVE_MASTERY_DEFAULTS.targetAccuracy,+ },+ };+}diff --git a/server/lib/postProgression.test.js b/server/lib/postProgression.test.jsnew file mode 100644index 0000000000..fda765ff2b--- /dev/null+++ b/server/lib/postProgression.test.js@@ -0,0 +1,157 @@+import { describe, it, expect } from 'vitest';+import {+ createProgression,+ PROGRESSION_MASTERY_DEFAULTS,+ clampLevel,+ COGNITIVE_LADDERS,+ COGNITIVE_LADDER_TYPES,+ COGNITIVE_MASTERY_DEFAULTS,+ cognitiveLadder,+ cognitiveLevelConfig,+ resolveCognitiveProgression,+} from './postProgression.js';++describe('clampLevel', () => {+ it('clamps into range and coerces non-integers to 0', () => {+ expect(clampLevel(-5, 4)).toBe(0);+ expect(clampLevel(999, 4)).toBe(4);+ expect(clampLevel(2, 4)).toBe(2);+ expect(clampLevel('x', 4)).toBe(0);+ expect(clampLevel(undefined, 4)).toBe(0);+ });+});++// A speed-gated ladder (mirrors the multiplication ladder's mastery contract:+// samples + accuracy + a per-level response-time target) exercised against the+// same matrix the multiplication suite uses, to prove the shared helper carries+// that behaviour.+describe('createProgression — speed-gated ladder', () => {+ const p = createProgression({+ levels: [[1, 1], [1, 2], [1, 1, 1], [2, 2]],+ describeLevel: level => `L${level}`,+ mastery: { minSamples: 12, targetAccuracy: 0.9, baseMsPerFactorDigit: 2200, minTargetMs: 4000 },+ speedTargetForLevel: (level, opts) => {+ const totalDigits = [[1, 1], [1, 2], [1, 1, 1], [2, 2]][level].reduce((a, b) => a + b, 0);+ return Math.max(opts.minTargetMs, opts.baseMsPerFactorDigit * totalDigits);+ },+ });++ it('speedTargetMs scales with total digit count, floored at minTargetMs', () => {+ expect(p.speedTargetMs(0)).toBe(2 * 2200); // [1,1] → 4400+ expect(p.speedTargetMs(3)).toBe(4 * 2200); // [2,2] → 8800+ expect(p.speedTargetMs(0, { baseMsPerFactorDigit: 100, minTargetMs: 4000 })).toBe(4000);+ });++ it('isLevelMastered gates on samples, accuracy AND speed', () => {+ const good = { samples: 12, accuracy: 0.95, avgResponseMs: 3000 };+ expect(p.isLevelMastered(good, 0)).toBe(true);+ expect(p.isLevelMastered({ ...good, samples: 5 }, 0)).toBe(false);+ expect(p.isLevelMastered({ ...good, accuracy: 0.7 }, 0)).toBe(false);+ expect(p.isLevelMastered({ ...good, avgResponseMs: 99999 }, 0)).toBe(false);+ // No timed samples → never "instant mastery" on a speed-gated ladder.+ expect(p.isLevelMastered({ samples: 20, accuracy: 1, avgResponseMs: 0 }, 0)).toBe(false);+ });++ it('resolveLevel advances past mastered rungs and stops at an unmastered gap', () => {+ const m = { samples: 20, accuracy: 1, avgResponseMs: 3000 };+ expect(p.resolveLevel({ 0: m, 1: m }).level).toBe(2);+ // A higher mastered rung must not let the walk skip an unmastered one.+ expect(p.resolveLevel({ 0: m, 2: m }).level).toBe(1);+ expect(p.resolveLevel({ '0': m }).level).toBe(1); // string keys+ });++ it('resolveLevel caps at the hardest rung and never demotes below the floor', () => {+ const m = { samples: 20, accuracy: 1, avgResponseMs: 1000 };+ const all = p.resolveLevel({ 0: m, 1: m, 2: m, 3: m });+ expect(all.level).toBe(3);+ expect(all.atHardest).toBe(true);+ // Empty window but earned rung 2 → holds at 2, lower rungs render mastered.+ const floored = p.resolveLevel({}, {}, 2);+ expect(floored.level).toBe(2);+ expect(floored.floorLevel).toBe(2);+ expect(floored.levels[0].mastered).toBe(true);+ expect(floored.levels[2].mastered).toBe(false);+ });+});++// An accuracy-only ladder (no speedTargetForLevel) — the cognitive contract:+// mastery is samples + accuracy, response time irrelevant.+describe('createProgression — accuracy-only ladder', () => {+ const p = createProgression({+ levels: ['a', 'b', 'c'],+ describeLevel: level => `L${level}`,+ mastery: { minSamples: 3, targetAccuracy: 0.85 },+ });++ it('masters on samples + accuracy alone, ignoring avgResponseMs', () => {+ expect(p.speedTargetMs(0)).toBeNull();+ expect(p.isLevelMastered({ samples: 3, accuracy: 0.9, avgResponseMs: 0 }, 0)).toBe(true);+ expect(p.isLevelMastered({ samples: 2, accuracy: 1 }, 0)).toBe(false);+ expect(p.isLevelMastered({ samples: 5, accuracy: 0.8 }, 0)).toBe(false);+ });++ it('resolveLevel walks up on sustained accuracy', () => {+ const m = { samples: 4, accuracy: 0.9 };+ expect(p.resolveLevel({ 0: m }).level).toBe(1);+ expect(p.resolveLevel({ 0: m, 1: m }).level).toBe(2);+ });+});++describe('PROGRESSION_MASTERY_DEFAULTS', () => {+ it('exposes the shared threshold shape', () => {+ expect(PROGRESSION_MASTERY_DEFAULTS.minSamples).toBe(12);+ expect(PROGRESSION_MASTERY_DEFAULTS.targetAccuracy).toBe(0.9);+ });+});++describe('cognitive ladders', () => {+ it('ladders exist for every skill drill but not reaction-time', () => {+ expect(COGNITIVE_LADDER_TYPES).toEqual(['n-back', 'digit-span', 'schulte-table', 'mental-rotation', 'stroop']);+ expect(cognitiveLadder('reaction-time')).toBeNull();+ expect(cognitiveLadder('nope')).toBeNull();+ });++ it('n-back raises n first (1→2→3) then squeezes stimulusMs', () => {+ const l = COGNITIVE_LADDERS['n-back'].levels;+ expect(l.map(r => r.n)).toEqual([1, 2, 3, 3, 3]);+ expect(l.map(r => r.stimulusMs)).toEqual([2500, 2500, 2500, 2000, 1600]);+ });++ it('digit-span grows forward then adds backward recall', () => {+ const l = COGNITIVE_LADDERS['digit-span'].levels;+ expect(l[0]).toMatchObject({ direction: 'forward', startLength: 4 });+ expect(l[l.length - 1]).toMatchObject({ direction: 'backward', maxLength: 9 });+ });++ 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 });+ expect(cognitiveLevelConfig('schulte-table', 1)).toEqual({ size: 5 });+ expect(cognitiveLevelConfig('reaction-time', 0)).toEqual({});+ // Mutating the result must not corrupt the ladder.+ const cfg = cognitiveLevelConfig('n-back', 0);+ cfg.n = 99;+ expect(COGNITIVE_LADDERS['n-back'].levels[0].n).toBe(1);+ });++ it('resolveCognitiveProgression maps a fresh user to level 0 with rung config + thresholds', () => {+ const r = resolveCognitiveProgression('n-back', {}, 0);+ expect(r.type).toBe('n-back');+ 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.levels).toHaveLength(5);+ });++ it('resolveCognitiveProgression advances on sustained balanced accuracy', () => {+ const m = { samples: 3, accuracy: 0.9, avgResponseMs: 0 };+ const r = resolveCognitiveProgression('n-back', { 0: m, 1: m }, 0);+ expect(r.level).toBe(2); // 1-back and 2-back mastered → sits on 3-back+ expect(r.config).toEqual({ n: 3, stimulusMs: 2500 });+ });++ 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 b6ef7ceb44..70fac75477 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -106,10 +106,14 @@ const drillTypeConfigSchema = z.object({// keeps a conservative fixed floor of 6 and lets the generator clamp up.// (timeLimitSec above is validated but NOT enforced for these drill types —// they're self-paced/stimulus-driven; see PostCognitiveDrillRunner.jsx.)- // No stimulusMs/showMs here — no UI ever set them (issue #2008), so they were- // dead validated-but-unreachable knobs; the generators (meatspacePostCognitive.js)- // keep their own internal defaults regardless.+ // stimulusMs (n-back) / showMs (digit-span) are the presentation-speed knobs.+ // The progressive ladder (default ON) drives them per rung; manual mode+ // (progressive off) exposes them in the config UI (issue #2095), so they must+ // survive validation. Bounds mirror the generator clamps in+ // meatspacePostCognitive.js (generateNBack / generateDigitSpan).n: z.number().int().min(1).max(3).optional(),+ stimulusMs: z.number().int().min(1000).max(5000).optional(),+ showMs: z.number().int().min(400).max(4000).optional(),length: z.number().int().min(6).max(60).optional(),direction: z.enum(['forward', 'backward']).optional(),startLength: z.number().int().min(3).max(9).optional(),diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.jsindex d0211a1450..a9ce42cf3e 100644--- a/server/routes/meatspacePostRoutes.js+++ b/server/routes/meatspacePostRoutes.js@@ -171,6 +171,17 @@ router.get('/post/multiplication-progress', asyncHandler(async (req, res) => {res.json(progress);}));+/**+ * GET /api/meatspace/post/cognitive-progress+ * Per-drill progressive-ladder level + per-rung mastery for the laddered+ * cognitive drills (n-back / digit-span / schulte / mental-rotation / stroop),+ * keyed by drill type, so the config UI can show each drill's current rung.+ */+router.get('/post/cognitive-progress', asyncHandler(async (req, res) => {+ const progress = await postService.getCognitiveProgress();+ res.json(progress);+}));+/*** GET /api/meatspace/post/adaptive-preview* Transparent per-type preview of effective adaptive difficulty for math drills,diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex 20ea9806a5..8492543084 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -13,6 +13,13 @@ import { deepMerge, isPlainObject } from '../lib/objects.js';import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES } from '../lib/postValidation.js';import { adaptDrillConfig, ADAPTIVE_SPECS, ADAPTIVE_DEFAULTS } from '../lib/postAdaptive.js';import { resolveMultiplicationLevel, MASTERY_DEFAULTS } from '../lib/postMultiplicationLadder.js';+import {+ cognitiveLadder,+ cognitiveLevelConfig,+ resolveCognitiveProgression,+ COGNITIVE_LADDER_TYPES,+ COGNITIVE_MASTERY_DEFAULTS,+} from '../lib/postProgression.js';import { COGNITIVE_DRILL_TYPES, generateCognitiveDrill, scoreCognitiveDrill } from './meatspacePostCognitive.js';import { advanceScheduleFromSession, mergeMasteryFromSession } from './meatspacePostMemory.js';@@ -61,14 +68,18 @@ const DEFAULT_CONFIG = {// No provider calls — enabled by default since they're free to run. No// timeLimitSec — these drills are self-paced/stimulus-driven and never// enforce a countdown (see client PostCognitiveDrillRunner.jsx / issue #2008).+ // `progressive` (default ON for laddered drills) ramps difficulty via the+ // per-skill ladders in server/lib/postProgression.js instead of a fixed knob;+ // the manual knobs (incl. stimulusMs/showMs) are the fallback when it's off.+ // reaction-time is a measurement baseline (no ladder, no progressive).cognitive: {enabled: true,drillTypes: {- 'n-back': { enabled: true, n: 2, length: 20 },- 'digit-span': { enabled: true, direction: 'forward', startLength: 3, maxLength: 8 },- 'stroop': { enabled: true, count: 15 },- 'schulte-table': { enabled: true, size: 5 },- 'mental-rotation': { enabled: true, count: 8 },+ '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 },+ 'schulte-table': { enabled: true, progressive: true, size: 5 },+ 'mental-rotation': { enabled: true, progressive: true, count: 8 },'reaction-time': { enabled: true, mode: 'simple', count: 15, minDelayMs: 1000, maxDelayMs: 3000, choices: 3 }}},@@ -654,6 +665,72 @@ export async function getMultiplicationProgress() {return { ...progression, windowDays: MASTERY_DEFAULTS.windowDays, thresholds: { minSamples: MASTERY_DEFAULTS.minSamples, targetAccuracy: MASTERY_DEFAULTS.targetAccuracy } };}+/**+ * 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).+ *+ * 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}>}+ */+async function getCognitiveLevelStats(type, windowDays = COGNITIVE_MASTERY_DEFAULTS.windowDays) {+ const sessions = await getPostSessions();+ let cutoffStr = null;+ if (windowDays > 0) {+ const cutoff = new Date();+ cutoff.setDate(cutoff.getDate() - windowDays);+ cutoffStr = cutoff.toISOString().split('T')[0];+ }++ const byLevel = {};+ let floorLevel = 0;+ for (const session of sessions) {+ for (const task of session.tasks || []) {+ if (task.type !== type) continue;+ const level = Number.isInteger(task.config?.level) ? task.config.level : null;+ if (level == null) continue; // pre-#2095 tasks carry no level+ // All-time floor: any reached (non-empty) drill at this level proves the+ // user earned the rung, regardless of the window.+ const reached = ((task.totalCount ?? (task.questions?.length || 0)) > 0);+ if (reached && level > floorLevel) floorLevel = level;+ // Mastery stats are windowed.+ if (cutoffStr && session.date < cutoffStr) continue;+ const acc = Number.isFinite(task.accuracy) ? task.accuracy : null;+ if (acc == null) continue;+ const bucket = byLevel[level] || (byLevel[level] = { samples: 0, accSum: 0 });+ bucket.samples += 1;+ bucket.accSum += acc;+ }+ }++ 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 };+ }+ return { stats, floorLevel };+}++/**+ * Resolve the current progressive difficulty for every laddered cognitive drill+ * from history — the current rung + per-rung mastery for the config/preview UI.+ * Keyed by drill type (`{ 'n-back': {...}, 'digit-span': {...}, … }`).+ */+export async function getCognitiveProgress() {+ const out = {};+ for (const type of COGNITIVE_LADDER_TYPES) {+ const { stats, floorLevel } = await getCognitiveLevelStats(type);+ out[type] = resolveCognitiveProgression(type, stats, floorLevel);+ }+ return out;+}+/*** Resolve the effective drill config for generation.*@@ -689,6 +766,27 @@ 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+ // (incl. stimulusMs/showMs) pass through unchanged. reaction-time has no+ // ladder and always passes through (issue #2095).+ if (cognitiveLadder(type)) {+ const cogCfg = config?.cognitive?.drillTypes?.[type] || {};+ if (cogCfg.progressive !== false) {+ const { stats, floorLevel } = await getCognitiveLevelStats(type);+ const progression = resolveCognitiveProgression(type, stats, floorLevel);+ const effective = {+ ...requestedConfig,+ ...cognitiveLevelConfig(type, progression.level),+ level: progression.level,+ };+ return { config: effective, adaptive: null, progression };+ }+ return { config: requestedConfig, adaptive: null };+ }+if (!config?.adaptive?.enabled || !ADAPTIVE_SPECS[type]) {return { config: requestedConfig, adaptive: null };}diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.jsindex 7a26b5d11c..03574b6c57 100644--- a/server/services/meatspacePost.test.js+++ b/server/services/meatspacePost.test.js@@ -28,6 +28,8 @@ import {postConfigEvents,resolveDrillConfig,getMultiplicationProgress,+ getCognitiveProgress,+ generateDrill,getPostStats,deriveTaskAccuracy,deriveTaskCompletion,@@ -852,6 +854,139 @@ describe('resolveDrillConfig — progressive multiplication', () => {});});+// =============================================================================+// PROGRESSIVE COGNITIVE LADDERS — resolveDrillConfig / getCognitiveProgress /+// difficulty stamping through submitPostSession (issue #2095)+// =============================================================================++describe('progressive cognitive drills', () => {+ const today = new Date().toISOString().split('T')[0];+ const oldDate = new Date(Date.now() - 60 * 86400000).toISOString().split('T')[0];++ // A completed cognitive drill at `level` with a given task-level accuracy —+ // the shape getCognitiveLevelStats buckets by (accuracy-only mastery).+ function cognitiveSession(type, level, accuracy, date = today, count = 20) {+ return {+ date,+ tasks: [{+ module: 'cognitive',+ type,+ config: { level },+ accuracy,+ totalCount: count,+ questions: Array.from({ length: count }, () => ({ answered: 'x' })),+ }],+ };+ }++ function mockSessions(sessions, configOverride) {+ readJSONFile.mockImplementation((path, defaultValue) => {+ const p = String(path);+ if (p.includes('post-sessions')) return Promise.resolve({ sessions });+ if (p.includes('post-config')) return Promise.resolve(configOverride ?? defaultValue);+ return Promise.resolve(defaultValue);+ });+ }++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('starts a fresh user at n-back level 0 (1-back) and stamps the rung knobs', async () => {+ mockSessions([]);+ const { config, progression } = await resolveDrillConfig('n-back', { length: 20 });+ expect(progression.level).toBe(0);+ expect(config.level).toBe(0);+ expect(config.n).toBe(1);+ expect(config.stimulusMs).toBe(2500);+ });++ it('advances a cognitive rung on sustained balanced accuracy', async () => {+ // 3 clean 1-back runs at 90% balanced accuracy → clears level 0.+ mockSessions([+ cognitiveSession('n-back', 0, 0.9),+ cognitiveSession('n-back', 0, 0.92),+ cognitiveSession('n-back', 0, 0.95),+ ]);+ const { config, progression } = await resolveDrillConfig('n-back', {});+ expect(progression.level).toBe(1);+ expect(config.n).toBe(2);+ });++ it('does not advance when accuracy is below the mastery bar', async () => {+ mockSessions([+ cognitiveSession('n-back', 0, 0.6),+ cognitiveSession('n-back', 0, 0.7),+ cognitiveSession('n-back', 0, 0.5),+ ]);+ const { progression } = await resolveDrillConfig('n-back', {});+ expect(progression.level).toBe(0);+ });++ it('never demotes below the earned floor when the window aged out', async () => {+ mockSessions([+ cognitiveSession('digit-span', 3, 0.9, oldDate),+ cognitiveSession('digit-span', 3, 0.95, oldDate),+ cognitiveSession('digit-span', 3, 0.9, oldDate),+ ]);+ const { progression, config } = await resolveDrillConfig('digit-span', {});+ expect(progression.level).toBe(3);+ expect(progression.floorLevel).toBe(3);+ expect(config.direction).toBe('backward');+ });++ it('passes config through unchanged when the drill Progressive toggle is off', async () => {+ mockSessions([], { cognitive: { drillTypes: { 'n-back': { progressive: false } } } });+ const { config, progression } = await resolveDrillConfig('n-back', { n: 3, stimulusMs: 1200 });+ expect(progression == null).toBe(true);+ expect(config).toEqual({ n: 3, stimulusMs: 1200 });+ });++ it('reaction-time has no ladder — always passes config through', async () => {+ mockSessions([]);+ const { config, progression } = await resolveDrillConfig('reaction-time', { mode: 'choice' });+ expect(progression == null).toBe(true);+ expect(config).toEqual({ mode: 'choice' });+ });++ it('generateDrill stamps the resolved level into the generated cognitive config', async () => {+ mockSessions([]);+ const { config } = await resolveDrillConfig('n-back', { length: 12 });+ const drill = generateDrill('n-back', config);+ expect(drill.config.level).toBe(0);+ expect(drill.config.n).toBe(1);+ });++ it('getCognitiveProgress separates per-level history (n=2 vs n=3 recoverable)', async () => {+ mockSessions([+ cognitiveSession('n-back', 1, 0.9),+ cognitiveSession('n-back', 1, 0.95),+ cognitiveSession('n-back', 1, 0.92),+ ]);+ const progress = await getCognitiveProgress();+ expect(progress['n-back'].level).toBe(2); // level-1 mastered → sits on level 2+ expect(progress['n-back'].levels[1].mastered).toBe(true);+ expect(progress['n-back'].levels[2].mastered).toBe(false);+ // Every laddered type reports; reaction-time is absent.+ expect(Object.keys(progress).sort()).toEqual(['digit-span', 'mental-rotation', 'n-back', 'schulte-table', 'stroop']);+ });++ it('difficulty stamp survives submitPostSession (stored task carries config.level)', async () => {+ mockSessions([]);+ const { config } = await resolveDrillConfig('schulte-table', {});+ const drill = generateDrill('schulte-table', config);+ // Client submits the served drill's config (with level) + drillData.+ const questions = drill.cells.map((_, i) => ({ index: i, answered: i + 1, responseMs: 500 }));+ const session = await submitPostSession({+ modules: ['cognitive'],+ tasks: [{ module: 'cognitive', type: 'schulte-table', config: drill.config, drillData: drill, questions, totalMs: 5000 }],+ });+ const stored = session.tasks[0];+ expect(stored.config.level).toBe(0);+ expect(Number.isFinite(stored.accuracy)).toBe(true);+ });+});+// =============================================================================// SCORING MODEL: accuracy vs speed separation, adaptive signal, legacy fallback// (issue #2094)diff --git a/server/services/meatspacePostCognitive.js b/server/services/meatspacePostCognitive.jsindex 1ad0e5d9fb..a0d8e849e6 100644--- a/server/services/meatspacePostCognitive.js+++ b/server/services/meatspacePostCognitive.js@@ -358,22 +358,37 @@ export function generateReactionTime(config = {}) {}export function generateCognitiveDrill(type, config = {}) {+ let drill;switch (type) {case 'n-back':- return generateNBack(config);+ drill = generateNBack(config);+ break;case 'digit-span':- return generateDigitSpan(config);+ drill = generateDigitSpan(config);+ break;case 'stroop':- return generateStroop(config);+ drill = generateStroop(config);+ break;case 'schulte-table':- return generateSchulteTable(config);+ drill = generateSchulteTable(config);+ break;case 'mental-rotation':- return generateMentalRotation(config);+ drill = generateMentalRotation(config);+ break;case 'reaction-time':- return generateReactionTime(config);+ drill = generateReactionTime(config);+ break;default:return null;}+ // Stamp the effective progression level into the generated drill's config so+ // it round-trips through the client and is persisted per-task on session+ // submit — the difficulty stamp that lets stats bucket by rung (n=2 vs n=3),+ // exactly as multiplication stamps `config.level` (issue #2095).+ if (drill && Number.isInteger(config.level)) {+ drill.config = { ...drill.config, level: config.level };+ }+ return drill;}// =============================================================================