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
Ramp up POST multiplication drills via a mastery-gated ladder
Adam Eivy8d415b97cf2f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex bf40e6b37f..18f4c4d86c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,4 +6,5 @@## MeatSpace POST+- **Multiplication drills now ramp up instead of starting hard.** The mental-math multiplication drill used to open at a fixed 2-digit × 2-digit difficulty (e.g. `566 × 191`) for everyone. It now climbs a mastery-gated ladder — `1×1` → `1×2` → `1×1×1` → `2×2` → … — starting at single-digit × single-digit and advancing to the next rung only after you answer a level quickly *and* accurately (≥90% correct within a per-rung speed target). The drill header and the config page show your current rung and per-level mastery. On by default; turn off "Progressive difficulty" on the Multiplication card to go back to the manual Max Digits setting.- **Morse trainer audio now works on mobile Safari.** iOS Safari starts the Web Audio context suspended and only unlocks it once `resume()` fully settles. The trainer fired `resume()` without awaiting it, so the first tones were scheduled against a still-suspended clock and never sounded on iPhone/iPad. It now awaits the resume before scheduling any tone (matching the app's other audio modules), so Copy, Head Copy, and Send-mode keying all produce sound on mobile Safari.diff --git a/client/src/components/meatspace/post/PostDrillConfig.jsx b/client/src/components/meatspace/post/PostDrillConfig.jsxindex 0df2807cc1..4511944462 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 } from '../../../services/api';+import { updatePostConfig, getProviders, getPostAdaptivePreview, getPostMultiplicationProgress } from '../../../services/api';import toast from '../../ui/Toast';import { FormField } from '../../ui/FormField';import { filterSelectableModels, enabledApiProviderFilter } from '../../../utils/providers';@@ -253,7 +253,41 @@ function AdaptiveBadge({ info }) {);}-function DrillCard({ meta, drillConfig, enabled, accent, onToggle, onUpdateField, adaptiveInfo }) {+// 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 }) {+ if (!info || !Array.isArray(info.levels)) return null;+ const pct = Math.round((info.thresholds?.targetAccuracy ?? 0.9) * 100);+ return (+ <div className="mt-3 space-y-1.5">+ <div className="flex items-center gap-1.5 text-xs text-port-accent">+ <TrendingUp size={12} className="shrink-0" />+ <span>+ Level {info.level + 1} of {info.levels.length} · {info.label}+ {info.atHardest && info.currentMastered ? ' (mastered)' : ''}+ </span>+ </div>+ <div className="flex items-center gap-1" aria-hidden="true">+ {info.levels.map(l => (+ <span+ key={l.level}+ title={`${l.label}${l.mastered ? ' — mastered' : l.level === info.level ? ' — current' : ''}`}+ className={`h-1.5 flex-1 rounded-full ${+ l.mastered ? 'bg-port-success' : l.level === info.level ? 'bg-port-accent' : 'bg-port-border'+ }`}+ />+ ))}+ </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.+ </p>+ </div>+ );+}++function DrillCard({ meta, drillConfig, enabled, accent, onToggle, onUpdateField, adaptiveInfo, progressive, onToggleProgressive, progressInfo }) {+ const supportsProgressive = typeof progressive === 'boolean';+ const hideMaxDigits = 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 (@@ -281,9 +315,32 @@ function DrillCard({ meta, drillConfig, enabled, accent, onToggle, onUpdateField</button></div>+ {enabled && supportsProgressive && (+ <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>+ </div>+ <button+ type="button"+ role="switch"+ aria-checked={progressive}+ aria-label="Progressive difficulty"+ onClick={onToggleProgressive}+ className={`shrink-0 w-10 h-5 rounded-full transition-colors relative ${+ progressive ? toggleBg : 'bg-port-border'+ }`}+ >+ <div className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${+ progressive ? 'translate-x-5' : 'translate-x-0.5'+ }`} />+ </button>+ </div>+ )}+{enabled && (<div className="grid grid-cols-2 gap-3">- {meta.fields.map(field => (+ {meta.fields.filter(field => !(hideMaxDigits && field.key === 'maxDigits')).map(field => (<FormField key={field.key} label={field.label} labelClassName="text-xs text-gray-500 mb-1 block">{field.type === 'select' ? (<select@@ -310,7 +367,8 @@ function DrillCard({ meta, drillConfig, enabled, accent, onToggle, onUpdateField</div>)}- {enabled && <AdaptiveBadge info={adaptiveInfo} />}+ {enabled && supportsProgressive && progressive && <ProgressiveBadge info={progressInfo} />}+ {enabled && !(supportsProgressive && progressive) && <AdaptiveBadge info={adaptiveInfo} />}</div>);}@@ -341,6 +399,7 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {() => config?.adaptive?.enabled === true);const [adaptivePreview, setAdaptivePreview] = useState(null);+ const [multiplicationProgress, setMultiplicationProgress] = useState(null);// Opt-in daily reminder — off by default; see server/services/meatspacePostReminder.js.const [reminderEnabled, setReminderEnabled] = useState(() => config?.reminder?.enabled === true@@ -368,6 +427,19 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {return () => { cancelled = true; };}, [adaptiveEnabled]);+ // Progressive multiplication ladder status — mirrors the drill runner's badge+ // so the config page shows the current rung + mastery before a session.+ // Progressive defaults ON (undefined → true), matching the server default.+ const multiplicationProgressive = drillTypes.multiplication?.progressive !== false;+ useEffect(() => {+ if (!multiplicationProgressive) { setMultiplicationProgress(null); return; }+ let cancelled = false;+ getPostMultiplicationProgress()+ .then(p => { if (!cancelled) setMultiplicationProgress(p); })+ .catch(err => console.warn('⚠️ Failed to load multiplication progress: ' + err.message));+ return () => { cancelled = true; };+ }, [multiplicationProgressive]);+function toggleDrill(type) {setDrillTypes(prev => ({...prev,@@ -375,6 +447,13 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {}));}+ function toggleProgressive() {+ setDrillTypes(prev => ({+ ...prev,+ multiplication: { ...prev.multiplication, progressive: !(prev.multiplication?.progressive !== false) }+ }));+ }+function updateField(type, key, value) {const coerced = value === '' || value === null || value === undefined? undefined@@ -542,6 +621,7 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {<div className={CARD_GRID}>{Object.entries(DRILL_META).map(([type, meta]) => {const drillConfig = drillTypes[type] || {};+ const isMultiplication = type === 'multiplication';return (<DrillCardkey={type}@@ -552,6 +632,9 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {onToggle={() => toggleDrill(type)}onUpdateField={(key, value) => updateField(type, key, value)}adaptiveInfo={adaptiveEnabled ? adaptivePreview?.[type] : null}+ progressive={isMultiplication ? multiplicationProgressive : undefined}+ onToggleProgressive={isMultiplication ? toggleProgressive : undefined}+ progressInfo={isMultiplication ? multiplicationProgress : null}/>);})}diff --git a/client/src/components/meatspace/post/PostDrillConfig.test.jsx b/client/src/components/meatspace/post/PostDrillConfig.test.jsxindex a2176c669e..19be611662 100644--- a/client/src/components/meatspace/post/PostDrillConfig.test.jsx+++ b/client/src/components/meatspace/post/PostDrillConfig.test.jsx@@ -5,11 +5,12 @@ vi.mock('../../../services/api', () => ({updatePostConfig: vi.fn(),getProviders: vi.fn(),getPostAdaptivePreview: vi.fn(),+ getPostMultiplicationProgress: vi.fn(),}));vi.mock('../../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));import PostDrillConfig from './PostDrillConfig';-import { updatePostConfig, getProviders, getPostAdaptivePreview } from '../../../services/api';+import { updatePostConfig, getProviders, getPostAdaptivePreview, getPostMultiplicationProgress } from '../../../services/api';// The 14 generatable LLM drill types (mirror server + client constants).const ALL_LLM_TYPES = [@@ -50,6 +51,18 @@ beforeEach(() => {getProviders.mockResolvedValue({ providers: [] });updatePostConfig.mockResolvedValue(config);getPostAdaptivePreview.mockResolvedValue({ enabled: false, drills: {} });+ getPostMultiplicationProgress.mockResolvedValue({+ level: 0,+ label: '1×1-digit',+ atHardest: false,+ currentMastered: false,+ levels: [+ { level: 0, label: '1×1-digit', mastered: false },+ { level: 1, label: '1×2-digit', mastered: false },+ ],+ thresholds: { minSamples: 12, targetAccuracy: 0.9 },+ windowDays: 30,+ });});describe('PostDrillConfig', () => {@@ -141,7 +154,14 @@ describe('PostDrillConfig', () => {multiplication: { type: 'multiplication', field: 'maxDigits', from: 2, to: 3, applied: true, score: 94, samples: 5, reason: 'harder' },},});- const withAdaptive = { ...config, adaptive: { enabled: true } };+ // Multiplication defaults to the progressive ladder (which supersedes the+ // adaptive badge on that card); turn it off here so the adaptive preview is+ // what renders for this test.+ const withAdaptive = {+ ...config,+ mentalMath: { drillTypes: { multiplication: { enabled: true, count: 10, progressive: false } } },+ adaptive: { enabled: true },+ };render(<PostDrillConfig config={withAdaptive} onSaved={vi.fn()} onBack={vi.fn()} />);expect(screen.getByRole('switch', { name: 'Adaptive difficulty' }).getAttribute('aria-checked')).toBe('true');await waitFor(() => expect(getPostAdaptivePreview).toHaveBeenCalled());@@ -169,6 +189,26 @@ describe('PostDrillConfig', () => {expect(screen.queryByText(/at max tolerance/)).toBeNull();});+ 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' });+ 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();+ // The fetched ladder status renders.+ await waitFor(() => expect(getPostMultiplicationProgress).toHaveBeenCalled());+ await waitFor(() => expect(screen.getByText(/Level 1 of 2 · 1×1-digit/)).toBeTruthy());+ });++ 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' }));+ 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('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/components/meatspace/post/PostDrillRunner.jsx b/client/src/components/meatspace/post/PostDrillRunner.jsxindex 9452a5bb47..82feab44de 100644--- a/client/src/components/meatspace/post/PostDrillRunner.jsx+++ b/client/src/components/meatspace/post/PostDrillRunner.jsx@@ -154,6 +154,11 @@ export default function PostDrillRunner({ session }) {<div className="flex items-center justify-between text-sm text-gray-400"><span className={isTraining ? 'text-port-accent-2' : ''}>{DRILL_LABELS[currentDrill.type] || currentDrill.type}+ {currentDrill.progression && (+ <span className="ml-2 text-xs text-port-accent">+ Lvl {currentDrill.progression.level + 1} · {currentDrill.progression.label}+ </span>+ )}{isTraining && ' — Training'}</span><span>Drill {currentDrillIndex + 1} of {drillCount}</span>diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.jsindex 22e52e4820..2c436991cd 100644--- a/client/src/services/apiMeatspace.js+++ b/client/src/services/apiMeatspace.js@@ -187,6 +187,7 @@ export const submitPostSession = (data, options = {}) => request('/meatspace/pos});export 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 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 4762f96fb7..ec50842515 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -214,6 +214,7 @@ 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. || `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 0fd1fa1795..76e9ba10af 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -189,6 +189,7 @@ export * from './navManifest.js';export * from './personaTraitBlend.js';export * from './pipelineIssueOrder.js';export * from './postAdaptive.js';+export * from './postMultiplicationLadder.js';export * from './planIds.js';export * from './renderSlot.js';export * from './telegramClient.js';diff --git a/server/lib/postMultiplicationLadder.js b/server/lib/postMultiplicationLadder.jsnew file mode 100644index 0000000000..c0b4276c03--- /dev/null+++ b/server/lib/postMultiplicationLadder.js@@ -0,0 +1,144 @@+/**+ * POST progressive multiplication ladder (pure, side-effect-free).+ *+ * The plain multiplication drill used to start at a fixed 2-digit × 2-digit+ * difficulty (e.g. `56 × 91`) for everyone, which is far too hard as a warm-up.+ * This module replaces that with a mastery-gated difficulty ladder: a new user+ * starts at single-digit × single-digit and only climbs to the next rung once+ * they have demonstrated *speed* mastery (fast AND accurate) at the current one.+ *+ * The ladder grows the way the user asked for it: add a digit, then add a+ * factor, alternating so mental load rises gently rather than jumping straight+ * to large products.+ *+ * Unlike the generic `postAdaptive.js` knob (which only tunes a symmetric+ * `maxDigits`), this ladder can express asymmetric (1×2) and multi-factor+ * (1×1×1) rungs, which is what a real "ramp up" needs.+ *+ * 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.+ */++// 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+// progression is explicit and easy to reason about / test.+export const MULTIPLICATION_LADDER = [+ [1, 1], // 7 × 8+ [1, 2], // 7 × 84+ [1, 1, 1], // 6 × 7 × 8+ [2, 2], // 56 × 84+ [1, 2, 2], // 7 × 56 × 84+ [2, 3], // 56 × 842+ [1, 1, 1, 1], // 6 × 7 × 8 × 9+ [3, 3], // 566 × 191+];++export const MAX_MULTIPLICATION_LEVEL = MULTIPLICATION_LADDER.length - 1;++export const MASTERY_DEFAULTS = {+ // Answered questions accumulated at a level before it can be judged mastered.+ // ~1–2 sessions of the default 10-question drill.+ minSamples: 12,+ // Fraction of answered questions that must be correct.+ targetAccuracy: 0.9,+ // Speed target scales with total digit count so harder rungs get more time.+ // A [1,1] rung (2 total digits) targets ~4.4s but is floored at minTargetMs.+ baseMsPerFactorDigit: 2200,+ minTargetMs: 4000,+ // Stats window (days) the mastery signal is read over.+ windowDays: 30,+};++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]+ */+export function ladderFactors(level) {+ return MULTIPLICATION_LADDER[clampMultiplicationLevel(level)];+}++/**+ * Short human label for a level, e.g. `1×2-digit` or `1×1×1-digit`.+ */+export function describeMultiplicationLevel(level) {+ return `${ladderFactors(level).join('×')}-digit`;+}++/**+ * 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);+}++/**+ * Whether a level's aggregated stat clears the mastery bar: enough samples,+ * high accuracy, and average response time within the level's speed target.+ * @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);+}++/**+ * Resolve the user's current ladder level from per-level performance stats.+ *+ * Walks the ladder from the bottom and stops at the first rung the user has NOT+ * yet mastered — so they stay there accumulating fast-and-accurate reps until+ * the speed bar is cleared, then advance. Returns a transparent explainer with+ * every rung's status so the UI can show the ladder.+ *+ * @param {Record<number|string, {samples:number, accuracy:number, avgResponseMs:number}>} levelStats+ * @returns {{level, factors, label, atHardest, currentMastered, levels}}+ */+export function resolveMultiplicationLevel(levelStats = {}, opts = {}) {+ const options = { ...MASTERY_DEFAULTS, ...opts };+ 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),+ };+ });++ let level = 0;+ while (level < MAX_MULTIPLICATION_LEVEL && levels[level].mastered) level += 1;++ const current = levels[level];+ return {+ level,+ factors: current.factors,+ label: current.label,+ atHardest: level >= MAX_MULTIPLICATION_LEVEL,+ currentMastered: current.mastered,+ levels,+ };+}diff --git a/server/lib/postMultiplicationLadder.test.js b/server/lib/postMultiplicationLadder.test.jsnew file mode 100644index 0000000000..2cff446e62--- /dev/null+++ b/server/lib/postMultiplicationLadder.test.js@@ -0,0 +1,123 @@+import { describe, it, expect } from 'vitest';+import {+ MULTIPLICATION_LADDER,+ MAX_MULTIPLICATION_LEVEL,+ MASTERY_DEFAULTS,+ clampMultiplicationLevel,+ ladderFactors,+ describeMultiplicationLevel,+ speedTargetMs,+ isLevelMastered,+ resolveMultiplicationLevel,+} from './postMultiplicationLadder.js';++describe('multiplication ladder shape', () => {+ it('starts at single-digit × single-digit and grows monotonically in total digits', () => {+ expect(MULTIPLICATION_LADDER[0]).toEqual([1, 1]);+ expect(MULTIPLICATION_LADDER[1]).toEqual([1, 2]);+ expect(MULTIPLICATION_LADDER[2]).toEqual([1, 1, 1]);+ // Every rung has at least two factors and 1-4 digit factors.+ for (const factors of MULTIPLICATION_LADDER) {+ expect(factors.length).toBeGreaterThanOrEqual(2);+ for (const d of factors) {+ expect(d).toBeGreaterThanOrEqual(1);+ expect(d).toBeLessThanOrEqual(4);+ }+ }+ });++ it('MAX_MULTIPLICATION_LEVEL is the last index', () => {+ expect(MAX_MULTIPLICATION_LEVEL).toBe(MULTIPLICATION_LADDER.length - 1);+ });+});++describe('clampMultiplicationLevel', () => {+ it('clamps into range and coerces non-integers to 0', () => {+ expect(clampMultiplicationLevel(-5)).toBe(0);+ expect(clampMultiplicationLevel(999)).toBe(MAX_MULTIPLICATION_LEVEL);+ expect(clampMultiplicationLevel(2)).toBe(2);+ expect(clampMultiplicationLevel('x')).toBe(0);+ expect(clampMultiplicationLevel(undefined)).toBe(0);+ });+});++describe('ladderFactors / describeMultiplicationLevel', () => {+ it('returns the rung factors and a readable label', () => {+ expect(ladderFactors(0)).toEqual([1, 1]);+ expect(describeMultiplicationLevel(0)).toBe('1×1-digit');+ expect(describeMultiplicationLevel(2)).toBe('1×1×1-digit');+ });+});++describe('speedTargetMs', () => {+ it('scales with total digit count, floored at minTargetMs', () => {+ // [1,1] → 2 digits → 4400ms > floor 4000+ expect(speedTargetMs(0)).toBe(2 * MASTERY_DEFAULTS.baseMsPerFactorDigit);+ // [2,2] → 4 digits → 8800ms+ expect(speedTargetMs(3)).toBe(4 * MASTERY_DEFAULTS.baseMsPerFactorDigit);+ // Never below the floor even with a tiny base override.+ expect(speedTargetMs(0, { baseMsPerFactorDigit: 100, minTargetMs: 4000 })).toBe(4000);+ });+});++describe('isLevelMastered', () => {+ const good = { samples: 12, accuracy: 0.95, avgResponseMs: 3000 };+ it('true when samples, accuracy and speed all clear the bar', () => {+ expect(isLevelMastered(good, 0)).toBe(true);+ });+ it('false with too few samples', () => {+ expect(isLevelMastered({ ...good, samples: 5 }, 0)).toBe(false);+ });+ it('false when accuracy under target', () => {+ expect(isLevelMastered({ ...good, accuracy: 0.7 }, 0)).toBe(false);+ });+ it('false when too slow', () => {+ expect(isLevelMastered({ ...good, avgResponseMs: 99999 }, 0)).toBe(false);+ });+ it('false when no timed samples (avgResponseMs 0)', () => {+ expect(isLevelMastered({ samples: 20, accuracy: 1, avgResponseMs: 0 }, 0)).toBe(false);+ });+});++describe('resolveMultiplicationLevel', () => {+ it('starts a fresh user at level 0', () => {+ const r = resolveMultiplicationLevel({});+ expect(r.level).toBe(0);+ expect(r.factors).toEqual([1, 1]);+ expect(r.atHardest).toBe(false);+ expect(r.levels).toHaveLength(MULTIPLICATION_LADDER.length);+ });++ it('advances past mastered lower rungs to the first unmastered rung', () => {+ const mastered = { samples: 20, accuracy: 1, avgResponseMs: 3000 };+ const r = resolveMultiplicationLevel({ 0: mastered, 1: mastered });+ expect(r.level).toBe(2); // 0 and 1 mastered → sits on 2+ expect(r.levels[0].mastered).toBe(true);+ expect(r.levels[1].mastered).toBe(true);+ expect(r.levels[2].mastered).toBe(false);+ });++ it('does not skip an unmastered gap even if a higher rung looks mastered', () => {+ const mastered = { samples: 20, accuracy: 1, avgResponseMs: 3000 };+ // Level 0 mastered, level 1 NOT, level 2 mastered → must stop at 1.+ const r = resolveMultiplicationLevel({ 0: mastered, 2: mastered });+ expect(r.level).toBe(1);+ });++ it('caps at the hardest rung when everything is mastered', () => {+ const stats = {};+ for (let i = 0; i < MULTIPLICATION_LADDER.length; i++) {+ stats[i] = { samples: 20, accuracy: 1, avgResponseMs: 1000 };+ }+ const r = resolveMultiplicationLevel(stats);+ expect(r.level).toBe(MAX_MULTIPLICATION_LEVEL);+ expect(r.atHardest).toBe(true);+ expect(r.currentMastered).toBe(true);+ });++ it('accepts string-keyed level stats', () => {+ const mastered = { samples: 20, accuracy: 1, avgResponseMs: 3000 };+ const r = resolveMultiplicationLevel({ '0': mastered });+ expect(r.level).toBe(1);+ });+});diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex f2e2770156..0b7e12f679 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -88,6 +88,13 @@ const drillTypeConfigSchema = z.object({timeLimitSec: z.number().int().min(10).max(600).optional(),count: z.number().int().min(1).max(50).optional(),maxDigits: z.number().int().min(1).max(4).optional(),+ // Progressive multiplication ladder (server/lib/postMultiplicationLadder.js).+ // `progressive` is the config toggle; `level`/`factors` are server-computed+ // effective config stamped into the generated drill (and stored per-task on+ // session submit), so they must survive validation on the round-trip.+ progressive: z.boolean().optional(),+ level: z.number().int().min(0).max(50).optional(),+ factors: z.array(z.number().int().min(1).max(4)).min(2).max(6).optional(),bases: z.array(z.number().int().min(2).max(20)).min(1).optional(),maxExponent: z.number().int().min(2).max(20).optional(),tolerancePct: z.number().min(1).max(50).optional(),diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.jsindex f5d9b5d362..4edf62fa83 100644--- a/server/routes/meatspacePostRoutes.js+++ b/server/routes/meatspacePostRoutes.js@@ -146,15 +146,28 @@ router.post('/post/drill', asyncHandler(async (req, res) => {// Adaptive difficulty (opt-in): when the Adaptive toggle is on, math drill// params are nudged from recent scored performance; otherwise config passes// through unchanged. Attaches an `adaptive` explainer when an adjustment ran.- const { config: effectiveConfig, adaptive } = await postService.resolveDrillConfig(data.type, data.config);+ const { config: effectiveConfig, adaptive, progression } = await postService.resolveDrillConfig(data.type, data.config);const drill = postService.generateDrill(data.type, effectiveConfig);if (!drill) {throw new ServerError('Unknown drill type', { status: 400, code: 'INVALID_DRILL_TYPE' });}if (adaptive) drill.adaptive = adaptive;+ // Progressive multiplication ladder explainer (current level + per-rung mastery)+ // so the drill runner can show which rung the user is on and why.+ if (progression) drill.progression = progression;res.json(drill);}));+/**+ * GET /api/meatspace/post/multiplication-progress+ * Current progressive-multiplication ladder level + per-rung mastery status,+ * so the config UI can show the ramp before a session starts.+ */+router.get('/post/multiplication-progress', asyncHandler(async (req, res) => {+ const progress = await postService.getMultiplicationProgress();+ 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 c446155694..7997b9e716 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -12,6 +12,7 @@ import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.jsimport { 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 { COGNITIVE_DRILL_TYPES, generateCognitiveDrill, scoreCognitiveDrill } from './meatspacePostCognitive.js';import { advanceScheduleFromSession, mergeMasteryFromSession } from './meatspacePostMemory.js';@@ -34,7 +35,12 @@ const DEFAULT_CONFIG = {drillTypes: {'doubling-chain': { enabled: true, steps: 8, timeLimitSec: 60 },'serial-subtraction': { enabled: true, steps: 10, subtrahend: 7, startRange: [100, 200], timeLimitSec: 90 },- 'multiplication': { enabled: true, count: 10, maxDigits: 2, timeLimitSec: 120 },+ // `progressive` (default ON) makes multiplication ramp up a mastery-gated+ // difficulty ladder (server/lib/postMultiplicationLadder.js) starting at+ // single-digit × single-digit, instead of jumping straight to the fixed+ // `maxDigits` difficulty. `maxDigits` is retained as the fallback for when+ // a user turns the progressive ladder off.+ 'multiplication': { enabled: true, count: 10, maxDigits: 2, progressive: true, timeLimitSec: 120 },'powers': { enabled: true, bases: [2, 3, 5], maxExponent: 10, count: 8, timeLimitSec: 90 },'estimation': { enabled: true, count: 5, tolerancePct: 10, timeLimitSec: 120 }}@@ -366,16 +372,42 @@ export function generateSerialSubtraction(start, subtrahend = 7, steps = 10, stareturn { type: 'serial-subtraction', config: { startValue: startVal, subtrahend, steps }, questions };}-export function generateMultiplication(count = 10, maxDigits = 2) {- const maxVal = Math.pow(10, maxDigits) - 1;- const minVal = maxDigits > 1 ? Math.pow(10, maxDigits - 1) : 1;+// Random integer with exactly `digits` digits (1 → 1-9, 2 → 10-99, …).+function randInt(digits) {+ const maxVal = Math.pow(10, digits) - 1;+ const minVal = digits > 1 ? Math.pow(10, digits - 1) : 1;+ return Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;+}++/**+ * Generate a multiplication drill.+ *+ * Two shapes:+ * - Progressive ladder: pass `factors` (an array of per-factor digit counts,+ * e.g. `[1, 2]` or `[1, 1, 1]`) and, optionally, the `level` that produced it+ * (stamped into the returned config so scored history can bucket by level).+ * - Legacy: pass `maxDigits` for a symmetric two-factor problem (both factors+ * have `maxDigits` digits). Kept for when the progressive ladder is off.+ */+export function generateMultiplication(count = 10, maxDigits = 2, factors = null, level = null) {+ const useFactors = Array.isArray(factors) && factors.length >= 2+ ? factors.map(d => Math.max(1, Math.min(4, Math.trunc(d))))+ : null;+ const digitPlan = useFactors || [maxDigits, maxDigits];const questions = [];for (let i = 0; i < count; i++) {- const a = Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;- const b = Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;- questions.push({ prompt: `${a} x ${b}`, expected: a * b });+ const nums = digitPlan.map(d => randInt(d));+ const expected = nums.reduce((product, n) => product * n, 1);+ questions.push({ prompt: nums.join(' x '), expected });+ }+ const config = { count };+ if (useFactors) {+ config.factors = useFactors;+ if (Number.isInteger(level)) config.level = level;+ } else {+ config.maxDigits = maxDigits;}- return { type: 'multiplication', config: { count, maxDigits }, questions };+ return { type: 'multiplication', config, questions };}export function generatePowers(bases, maxExponent = 10, count = 8) {@@ -422,7 +454,7 @@ export function generateDrill(type, config = {}) {case 'serial-subtraction':return generateSerialSubtraction(config.startValue, config.subtrahend, config.steps, config.startRange);case 'multiplication':- return generateMultiplication(config.count, config.maxDigits);+ return generateMultiplication(config.count, config.maxDigits, config.factors, config.level);case 'powers':return generatePowers(config.bases, config.maxExponent, config.count);case 'estimation':@@ -457,15 +489,95 @@ async function getAdaptiveSignal(type) {}/**- * Resolve the effective drill config for generation. When the Adaptive toggle- * is off (default), the caller's manual config is returned unchanged. When on,- * math drills are nudged from recent scored performance within clamped bounds.- * Non-math (LLM/memory) types and unsupported math types pass through untouched.+ * Aggregate multiplication performance per ladder level from scored history,+ * so the progressive ladder can decide whether each level has been *speed*+ * mastered. Only answered questions count as samples; each contributes its+ * correctness and clamped response time.+ *+ * @returns {Promise<Record<number, {samples:number, accuracy:number, avgResponseMs:number}>>}+ */+async function getMultiplicationLevelStats(windowDays = 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 = {};+ for (const session of sessions) {+ if (cutoffStr && session.date < cutoffStr) continue;+ for (const task of session.tasks || []) {+ if (task.type !== 'multiplication') continue;+ const level = Number.isInteger(task.config?.level) ? task.config.level : null;+ if (level == null) continue; // legacy maxDigits-only tasks carry no level+ const bucket = byLevel[level] || (byLevel[level] = { samples: 0, correct: 0, totalResponseMs: 0 });+ for (const q of task.questions || []) {+ if (q?.answered == null) continue;+ bucket.samples += 1;+ if (q.correct) bucket.correct += 1;+ bucket.totalResponseMs += Math.max(0, q.responseMs || 0);+ }+ }+ }++ const stats = {};+ for (const [level, b] of Object.entries(byLevel)) {+ stats[level] = {+ samples: b.samples,+ accuracy: b.samples ? b.correct / b.samples : 0,+ avgResponseMs: b.samples ? b.totalResponseMs / b.samples : 0,+ };+ }+ return stats;+}++/**+ * Resolve the current progressive-multiplication difficulty from history.+ * Exposed for the config UI / route so it can show the ladder + mastery status.+ */+export async function getMultiplicationProgress() {+ const levelStats = await getMultiplicationLevelStats(MASTERY_DEFAULTS.windowDays);+ const progression = resolveMultiplicationLevel(levelStats);+ return { ...progression, windowDays: MASTERY_DEFAULTS.windowDays, thresholds: { minSamples: MASTERY_DEFAULTS.minSamples, targetAccuracy: MASTERY_DEFAULTS.targetAccuracy } };+}++/**+ * Resolve the effective drill config for generation.*- * @returns {{ config: object, adaptive: object|null }}+ * - Multiplication with the progressive ladder ON (default): factor structure+ * and difficulty come from mastery-gated level history, not the manual+ * `maxDigits`. Returns a `progression` explainer.+ * - Adaptive toggle ON: math drill params are nudged from recent scored+ * performance within clamped bounds. Returns an `adaptive` explainer.+ * - Otherwise (default): the caller's manual config passes through unchanged.+ *+ * @returns {{ config: object, adaptive: object|null, progression?: object|null }}*/export async function resolveDrillConfig(type, requestedConfig = {}) {const config = await getPostConfig();++ // Progressive multiplication ladder (default ON) — independent of the generic+ // Adaptive toggle. Selects the factor structure by speed-gated mastery so a+ // fresh user starts at single-digit × single-digit instead of a fixed hard+ // difficulty. `maxDigits` is stripped so generation uses `factors`.+ if (type === 'multiplication') {+ const mulCfg = config?.mentalMath?.drillTypes?.multiplication || {};+ if (mulCfg.progressive !== false) {+ const levelStats = await getMultiplicationLevelStats(MASTERY_DEFAULTS.windowDays);+ const progression = resolveMultiplicationLevel(levelStats);+ const { maxDigits: _drop, ...rest } = requestedConfig || {};+ const effective = {+ ...rest,+ count: rest.count ?? mulCfg.count ?? 10,+ level: progression.level,+ factors: progression.factors,+ };+ return { config: effective, adaptive: null, progression };+ }+ }+if (!config?.adaptive?.enabled || !ADAPTIVE_SPECS[type]) {return { config: requestedConfig, adaptive: null };}@@ -505,7 +617,15 @@ export async function getAdaptivePreview() {// =============================================================================export function computeExpectedFromPrompt(prompt) {- const match = prompt?.match(/^(-?\d+)\s*([+\-x^])\s*(-?\d+)$/);+ const s = typeof prompt === 'string' ? prompt.trim() : '';+ // Chained multiplication: "a x b" or "a x b x c x …" (progressive ladder can+ // emit 3+ factors). Handled first so a single "a x b" also flows through here.+ if (/^-?\d+(\s*x\s*-?\d+)+$/.test(s)) {+ const factors = s.split(/\s*x\s*/).map(n => parseInt(n, 10));+ if (factors.some(Number.isNaN)) return null;+ return factors.reduce((product, n) => product * n, 1);+ }+ const match = s.match(/^(-?\d+)\s*([+\-^])\s*(-?\d+)$/);if (!match) return null;const [, aStr, op, bStr] = match;const a = parseInt(aStr, 10);@@ -513,7 +633,6 @@ export function computeExpectedFromPrompt(prompt) {switch (op) {case '+': return a + b;case '-': return a - b;- case 'x': return a * b;case '^': return Math.pow(a, b);default: return null;}diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.jsindex 302b066cca..d121a5e12b 100644--- a/server/services/meatspacePost.test.js+++ b/server/services/meatspacePost.test.js@@ -26,6 +26,8 @@ import {submitPostSession,updatePostConfig,postConfigEvents,+ resolveDrillConfig,+ getMultiplicationProgress,} from './meatspacePost.js';// =============================================================================@@ -135,6 +137,46 @@ describe('generateMultiplication', () => {});});+// =============================================================================+// PROGRESSIVE MULTIPLICATION LADDER+// =============================================================================++describe('generateMultiplication — progressive factors', () => {+ it('honors an asymmetric factors array (1×2-digit)', () => {+ const result = generateMultiplication(20, 2, [1, 2], 1);+ expect(result.config.factors).toEqual([1, 2]);+ expect(result.config.level).toBe(1);+ expect(result.config.maxDigits).toBeUndefined();+ for (const q of result.questions) {+ const [a, b] = q.prompt.split(' x ').map(Number);+ expect(a).toBeGreaterThanOrEqual(1);+ expect(a).toBeLessThanOrEqual(9);+ expect(b).toBeGreaterThanOrEqual(10);+ expect(b).toBeLessThanOrEqual(99);+ expect(q.expected).toBe(a * b);+ }+ });++ it('supports three single-digit factors (1×1×1)', () => {+ const result = generateMultiplication(15, 2, [1, 1, 1], 2);+ for (const q of result.questions) {+ const nums = q.prompt.split(' x ').map(Number);+ expect(nums).toHaveLength(3);+ for (const n of nums) {+ expect(n).toBeGreaterThanOrEqual(1);+ expect(n).toBeLessThanOrEqual(9);+ }+ expect(q.expected).toBe(nums.reduce((p, n) => p * n, 1));+ }+ });++ it('falls back to symmetric maxDigits when no factors given', () => {+ const result = generateMultiplication(5, 3);+ expect(result.config.maxDigits).toBe(3);+ expect(result.config.factors).toBeUndefined();+ });+});+// =============================================================================// POWERS TESTS// =============================================================================@@ -237,6 +279,11 @@ describe('computeExpectedFromPrompt', () => {expect(computeExpectedFromPrompt('15 x 23')).toBe(345);});+ it('parses chained multiplication (3+ factors)', () => {+ expect(computeExpectedFromPrompt('6 x 7 x 8')).toBe(336);+ expect(computeExpectedFromPrompt('2 x 3 x 4 x 5')).toBe(120);+ });+it('parses powers', () => {expect(computeExpectedFromPrompt('2^8')).toBe(256);});@@ -669,3 +716,80 @@ describe('updatePostConfig — postConfigEvents', () => {expect(handler).toHaveBeenCalledTimes(1);});});++// =============================================================================+// PROGRESSIVE MULTIPLICATION — resolveDrillConfig / getMultiplicationProgress+// =============================================================================++describe('resolveDrillConfig — progressive multiplication', () => {+ const today = new Date().toISOString().split('T')[0];++ // Build a session with `n` answered multiplication questions at `level`, all+ // correct and fast (so the level clears the mastery bar).+ function masteredSession(level, n = 14, responseMs = 2500) {+ return {+ date: today,+ tasks: [{+ module: 'mental-math',+ type: 'multiplication',+ config: { level },+ questions: Array.from({ length: n }, () => ({ answered: 1, correct: true, responseMs })),+ }],+ };+ }++ 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 level 0 (single×single) and strips maxDigits', async () => {+ mockSessions([]);+ const { config, progression } = await resolveDrillConfig('multiplication', { count: 10, maxDigits: 2 });+ expect(progression).toBeTruthy();+ expect(progression.level).toBe(0);+ expect(config.level).toBe(0);+ expect(config.factors).toEqual([1, 1]);+ expect(config.maxDigits).toBeUndefined();+ expect(config.count).toBe(10);+ });++ it('advances to the next rung once the current one is speed-mastered', async () => {+ mockSessions([masteredSession(0)]);+ const { progression, config } = await resolveDrillConfig('multiplication', { count: 10 });+ expect(progression.level).toBe(1);+ expect(config.factors).toEqual([1, 2]);+ });++ it('does not advance when the level is accurate but too slow', async () => {+ mockSessions([masteredSession(0, 14, 60000)]);+ const { progression } = await resolveDrillConfig('multiplication', { count: 10 });+ expect(progression.level).toBe(0);+ });++ it('passes config through unchanged when progressive is turned off', async () => {+ mockSessions([], { mentalMath: { drillTypes: { multiplication: { progressive: false } } } });+ const { config, progression } = await resolveDrillConfig('multiplication', { count: 10, maxDigits: 2 });+ expect(progression == null).toBe(true);+ expect(config.maxDigits).toBe(2);+ expect(config.factors).toBeUndefined();+ });++ it('getMultiplicationProgress exposes the full ladder + thresholds', async () => {+ mockSessions([masteredSession(0)]);+ const progress = await getMultiplicationProgress();+ expect(progress.level).toBe(1);+ expect(Array.isArray(progress.levels)).toBe(true);+ expect(progress.levels[0].mastered).toBe(true);+ expect(progress.thresholds.minSamples).toBeGreaterThan(0);+ expect(progress.windowDays).toBeGreaterThan(0);+ });+});