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(post): opt-in adaptive difficulty for mental-math POST drills
[._.]/ Adam Eivy7a7aa200b1db
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 83b974c163..8b71ae1724 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -21,6 +21,7 @@- **[issue-1986] The POST launcher now fills the full desktop width.** The Power On Self Test launcher (`PostSessionLauncher.jsx`) previously wrapped every card in a single ~672px column (`max-w-2xl`), leaving a large dead gutter on wide monitors. It's now a responsive main-plus-sidebar grid (`lg:grid-cols-[minmax(0,1fr)_22rem]`, capped at `max-w-6xl`): the primary session flow — Today's Status, Session Mode toggle, Conditions, and the Start / Quick 5 Min buttons — stays in the left column above the fold, while the Mental Math / Wit & Memory drill summaries and Recent Sessions flow into the right sidebar. On mobile it collapses to a single readable column (Start buttons still prominent), the header action buttons wrap instead of overflowing, and the Start buttons stack on narrow screens. Layout-only — session start, Quick 5 Min, the Test/Train toggle, and condition tags are all unchanged. (`client/src/components/meatspace/post/PostSessionLauncher.jsx`, Closes #1986)- **[issue-1987] The POST drill config now exposes all 14 LLM drill types in a responsive, domain-grouped layout.** The Drill Configuration screen (`PostDrillConfig.jsx`) previously showed a single narrow column that only surfaced 5 of the 14 generatable LLM drills — so the entire **Imagination** family (What If?, Alternative Uses, Story Prompt, Invention Pitch, Reframe) plus **Compound Chain**, **Bridge Word**, **Double Meaning**, and **Idiom Twist** could be generated server-side but never toggled on for a session. All 14 are now shown as toggle cards grouped under **Wordplay / Verbal Agility / Imagination** section headers, laid out in a responsive grid (single column on mobile, up to three columns on desktop) instead of one page-length stack. Enabling any of them and saving persists via `PUT /post/config` and makes the drill appear in Full POST and Quick 5 Min sessions. (`client/src/components/meatspace/post/PostDrillConfig.jsx`, Closes #1987)- **[issue-1988] POST History is now a responsive analytics dashboard.** The History view (`client/src/components/meatspace/post/PostHistory.jsx`) was a single `max-w-3xl` column that stacked a lone overall-score line chart, a 3-up stat block, and the session table — surfacing only a fraction of what `getPostStats` already computes. It now fills desktop width and surfaces the full stats payload: a 4-up summary of **Sessions / Avg Score / Current Streak / Longest Streak**, a wide **Score Trend** line beside a horizontal **Avg by Domain** bar chart (each domain colored to match its `text-*-400` domain class), and a **Drill Breakdown** card that groups every drill's average into per-domain progress bars — so per-domain and per-drill averages plus streaks are visible without opening a single session. The five training domains (Mental Math / Memory / Wordplay / Verbal Agility / Imagination) are derived from each drill's *type* via `DRILL_TO_DOMAIN`, because the runners persist coarse module keys (`mental-math`, `llm-drills`) rather than domain keys — so all LLM drills split correctly across Wordplay/Verbal/Imagination instead of collapsing into one bucket. Mobile stays single-column; the 7/30/90/All range selector still drives every panel from one fetch. (Closes #1988)+- **[issue-1992] Opt-in adaptive difficulty for mental-math POST drills.** Math drill params (`steps` / `maxDigits` / `maxExponent` / estimation `tolerancePct`) were fixed values from config that never responded to how you were doing. A new **Adaptive difficulty** toggle in the Drill Configuration screen (default OFF, so existing installs are unchanged) makes each math drill nudge its primary difficulty knob from your recent scored performance: sustained high accuracy (≥90% over enough sessions) bumps it one step harder, repeated misses (≤50%) ease it back, all clamped to safe min/max bounds — and it won't move until it has enough scored samples to trust. The adjustment is a pure, unit-tested policy (`server/lib/postAdaptive.js`) applied server-side at drill-generation time, so manual config still wins whenever Adaptive is off. It's fully transparent: each math drill card shows the effective difficulty (e.g. "Adaptive: max digits 2 → 3 (harder · 94% recent)") via a new `GET /post/adaptive-preview` endpoint, so it's never a black box. (`server/lib/postAdaptive.js`, `server/services/meatspacePost.js`, `client/src/components/meatspace/post/PostDrillConfig.jsx`, Closes #1992)## Media Generationdiff --git a/client/src/components/meatspace/post/PostDrillConfig.jsx b/client/src/components/meatspace/post/PostDrillConfig.jsxindex 81d3d7f749..b8f0be1b02 100644--- a/client/src/components/meatspace/post/PostDrillConfig.jsx+++ b/client/src/components/meatspace/post/PostDrillConfig.jsx@@ -1,9 +1,33 @@import { useState, useEffect } from 'react';-import { ArrowLeft, Save, Brain } from 'lucide-react';-import { updatePostConfig, getProviders } from '../../../services/api';+import { ArrowLeft, Save, Brain, TrendingUp, TrendingDown, Minus } from 'lucide-react';+import { updatePostConfig, getProviders, getPostAdaptivePreview } from '../../../services/api';import toast from '../../ui/Toast';import { filterSelectableModels, enabledApiProviderFilter } from '../../../utils/providers';+// Human labels for the adaptive difficulty knob each math drill tunes.+const ADAPTIVE_FIELD_LABELS = {+ steps: 'steps', count: 'questions', maxDigits: 'max digits',+ maxExponent: 'max exponent', tolerancePct: 'tolerance %',+};++// Turn a server adaptive-preview result into a short, transparent status line+// so the effective difficulty is never a black box.+function describeAdaptive(info) {+ if (!info) return null;+ const field = ADAPTIVE_FIELD_LABELS[info.field] || info.field;+ const pct = info.score != null ? ` · ${info.score}% recent` : '';+ if (info.applied) {+ const harder = info.reason === 'harder';+ return { text: `Adaptive: ${field} ${info.from} → ${info.to} (${harder ? 'harder' : 'easier'})${pct}`, tone: harder ? 'up' : 'down' };+ }+ if (info.reason === 'insufficient-samples') {+ return { text: `Adaptive: warming up — needs more scored sessions`, tone: 'hold' };+ }+ if (info.reason === 'at-hardest') return { text: `Adaptive: at max ${field} ${info.from}${pct}`, tone: 'up' };+ if (info.reason === 'at-easiest') return { text: `Adaptive: at min ${field} ${info.from}${pct}`, tone: 'down' };+ return { text: `Adaptive: holding ${field} ${info.from}${pct}`, tone: 'hold' };+}+const DRILL_META = {'doubling-chain': {label: 'Doubling Chain',@@ -119,7 +143,20 @@ const LLM_DRILL_GROUPS = [const CARD_GRID = 'grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4';-function DrillCard({ meta, drillConfig, enabled, accent, onToggle, onUpdateField }) {+function AdaptiveBadge({ info }) {+ const status = describeAdaptive(info);+ if (!status) return null;+ const Icon = status.tone === 'up' ? TrendingUp : status.tone === 'down' ? TrendingDown : Minus;+ const color = status.tone === 'up' ? 'text-port-success' : status.tone === 'down' ? 'text-port-warning' : 'text-gray-500';+ return (+ <div className={`mt-3 flex items-center gap-1.5 text-xs ${color}`}>+ <Icon size={12} className="shrink-0" />+ <span>{status.text}</span>+ </div>+ );+}++function DrillCard({ meta, drillConfig, enabled, accent, onToggle, onUpdateField, adaptiveInfo }) {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 (@@ -164,6 +201,8 @@ function DrillCard({ meta, drillConfig, enabled, accent, onToggle, onUpdateField))}</div>)}++ {enabled && <AdaptiveBadge info={adaptiveInfo} />}</div>);}@@ -184,6 +223,10 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {const [llmModel, setLlmModel] = useState(() => config?.llmDrills?.model || '');+ const [adaptiveEnabled, setAdaptiveEnabled] = useState(+ () => config?.adaptive?.enabled === true+ );+ const [adaptivePreview, setAdaptivePreview] = useState(null);const [providers, setProviders] = useState([]);const [saving, setSaving] = useState(false);@@ -191,6 +234,19 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {getProviders().then(p => setProviders((p?.providers || []).filter(enabledApiProviderFilter))).catch(err => console.warn('⚠️ Failed to load providers: ' + err.message));}, []);+ // Load the effective-difficulty preview when Adaptive is on, so each math card+ // can show what a session would actually use. Reflects saved config + recent+ // performance from the server (not the unsaved form values), so it may lag an+ // edit until Save — the badge is a transparency aid, not a live simulator.+ useEffect(() => {+ if (!adaptiveEnabled) { setAdaptivePreview(null); return; }+ let cancelled = false;+ getPostAdaptivePreview()+ .then(p => { if (!cancelled) setAdaptivePreview(p?.drills || null); })+ .catch(err => console.warn('⚠️ Failed to load adaptive preview: ' + err.message));+ return () => { cancelled = true; };+ }, [adaptiveEnabled]);+function toggleDrill(type) {setDrillTypes(prev => ({...prev,@@ -232,6 +288,7 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {setSaving(true);const updated = await updatePostConfig({mentalMath: { drillTypes },+ adaptive: { enabled: adaptiveEnabled },llmDrills: {enabled: llmEnabled,providerId: llmProviderId || null,@@ -270,7 +327,31 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {{/* Mental Math Section */}<div className="space-y-3">- <h3 className="text-sm font-medium text-gray-500 uppercase tracking-wider">Mental Math</h3>+ <div className="flex items-center justify-between">+ <h3 className="text-sm font-medium text-gray-500 uppercase tracking-wider">Mental Math</h3>+ <div className="flex items-center gap-2">+ <span className="text-xs text-gray-400">Adaptive difficulty</span>+ <button+ type="button"+ role="switch"+ aria-checked={adaptiveEnabled}+ aria-label="Adaptive difficulty"+ onClick={() => setAdaptiveEnabled(v => !v)}+ className={`shrink-0 w-10 h-5 rounded-full transition-colors relative ${+ adaptiveEnabled ? 'bg-port-accent' : 'bg-port-border'+ }`}+ >+ <div className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${+ adaptiveEnabled ? 'translate-x-5' : 'translate-x-0.5'+ }`} />+ </button>+ </div>+ </div>+ {adaptiveEnabled && (+ <p className="text-xs text-gray-500">+ Math drills auto-adjust from your recent scores — high accuracy raises difficulty, repeated misses ease it, within safe bounds. Manual values below are the starting point.+ </p>+ )}<div className={CARD_GRID}>{Object.entries(DRILL_META).map(([type, meta]) => {const drillConfig = drillTypes[type] || {};@@ -283,6 +364,7 @@ export default function PostDrillConfig({ config, onSaved, onBack }) {accent="accent"onToggle={() => toggleDrill(type)}onUpdateField={(key, value) => updateField(type, key, value)}+ adaptiveInfo={adaptiveEnabled ? adaptivePreview?.[type] : null}/>);})}diff --git a/client/src/components/meatspace/post/PostDrillConfig.test.jsx b/client/src/components/meatspace/post/PostDrillConfig.test.jsxindex aa57200b89..0b0c625963 100644--- a/client/src/components/meatspace/post/PostDrillConfig.test.jsx+++ b/client/src/components/meatspace/post/PostDrillConfig.test.jsx@@ -4,11 +4,12 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react';vi.mock('../../../services/api', () => ({updatePostConfig: vi.fn(),getProviders: vi.fn(),+ getPostAdaptivePreview: vi.fn(),}));vi.mock('../../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));import PostDrillConfig from './PostDrillConfig';-import { updatePostConfig, getProviders } from '../../../services/api';+import { updatePostConfig, getProviders, getPostAdaptivePreview } from '../../../services/api';// The 14 generatable LLM drill types (mirror server + client constants).const ALL_LLM_TYPES = [@@ -48,6 +49,7 @@ beforeEach(() => {vi.clearAllMocks();getProviders.mockResolvedValue({ providers: [] });updatePostConfig.mockResolvedValue(config);+ getPostAdaptivePreview.mockResolvedValue({ enabled: false, drills: {} });});describe('PostDrillConfig', () => {@@ -122,4 +124,36 @@ describe('PostDrillConfig', () => {expect(screen.getByRole('switch', { name: 'Pun & Wordplay' }).getAttribute('aria-checked')).toBe('true');expect(screen.getByRole('switch', { name: 'Reframe' }).getAttribute('aria-checked')).toBe('false');});++ it('defaults the Adaptive difficulty toggle to off and persists it on save', async () => {+ render(<PostDrillConfig config={config} onSaved={vi.fn()} onBack={vi.fn()} />);+ const toggle = screen.getByRole('switch', { name: 'Adaptive difficulty' });+ expect(toggle.getAttribute('aria-checked')).toBe('false');+ fireEvent.click(screen.getByText('Save'));+ await waitFor(() => expect(updatePostConfig).toHaveBeenCalled());+ expect(updatePostConfig.mock.calls[0][0].adaptive).toEqual({ enabled: false });+ });++ it('reflects a saved adaptive.enabled=true, fetches the preview, and shows effective difficulty', async () => {+ getPostAdaptivePreview.mockResolvedValue({+ enabled: true,+ drills: {+ multiplication: { type: 'multiplication', field: 'maxDigits', from: 2, to: 3, applied: true, score: 94, samples: 5, reason: 'harder' },+ },+ });+ const withAdaptive = { ...config, 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());+ // The enabled multiplication card surfaces the effective (adapted) difficulty.+ await waitFor(() => expect(screen.getByText(/max digits 2 → 3 \(harder\)/)).toBeTruthy());+ });++ 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' }));+ fireEvent.click(screen.getByText('Save'));+ await waitFor(() => expect(updatePostConfig).toHaveBeenCalled());+ expect(updatePostConfig.mock.calls[0][0].adaptive).toEqual({ enabled: true });+ });});diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.jsindex ebafb1a2e3..2373ba9813 100644--- a/client/src/services/apiMeatspace.js+++ b/client/src/services/apiMeatspace.js@@ -184,6 +184,7 @@ export const submitPostSession = (data) => request('/meatspace/post/sessions', {body: JSON.stringify(data)});export const getPostStats = (days) => request(`/meatspace/post/stats${days != null ? `?days=${days}` : ''}`);+export const getPostAdaptivePreview = () => request('/meatspace/post/adaptive-preview');export const generatePostDrill = (type, config = {}, providerId, model) => 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 422acd7465..4037a92caa 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -41,7 +41,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `notesValidation.js` | Notes route schemas + safe-relative-path guard. || `peerSyncValidation.js` | Federated peer-sync wire/request schemas (push payload, subscribe, sync-now, pull-metadata). || `pipelineValidation.js` | Creative-production pipeline schemas (Writers Room works/folders/live-mode/drafts, story-bible character/place/object, editorial checks, storyboard shots/scenes, prompt-stage config, issue-list query). |-| `postValidation.js` | Social post schemas. |+| `postValidation.js` | MeatSpace POST (Power On Self Test) schemas — drill config (incl. adaptive toggle), drill generation/scoring, sessions, memory builder, training log. || `socketValidation.js` | Socket event payload schemas. || `storyBuilderValidation.js` | Unified Story Builder session/step schemas. || `telegramValidation.js` | Telegram bot config + test schemas. |@@ -213,6 +213,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `personaTraitBlend.js` | Digital-twin persona trait-blending (M34 P7). Blends a persona's `traitAdjustments` against the base twin's communication profile + Big-Five into a "Communication Calibration" directive. Mirrored to `client/src/lib/`. || `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. || `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 5401055f0d..ef17b6fc77 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -188,6 +188,7 @@ export * from './mediaItemKey.js';export * from './navManifest.js';export * from './personaTraitBlend.js';export * from './pipelineIssueOrder.js';+export * from './postAdaptive.js';export * from './planIds.js';export * from './renderSlot.js';export * from './telegramClient.js';diff --git a/server/lib/postAdaptive.js b/server/lib/postAdaptive.jsnew file mode 100644index 0000000000..4f6605a4ba--- /dev/null+++ b/server/lib/postAdaptive.js@@ -0,0 +1,109 @@+/**+ * POST adaptive difficulty policy (pure, side-effect-free).+ *+ * Given a math drill's base config and the user's recent performance signal+ * ({ score, samples }), nudge a single primary difficulty knob up or down within+ * clamped bounds. Opt-in: the caller only applies this when the user has enabled+ * the Adaptive toggle in POST config; when off, base config is the override.+ *+ * The signal is the average scored-session `score` (0-100) for the drill type+ * from `getPostStats().byDrill`, gated by `byDrillCount` samples so a single+ * lucky/unlucky run can't swing difficulty.+ */++// One primary difficulty knob per math drill type. `harderIsHigher` flips the+// direction for knobs where a LOWER value is harder (estimation tolerance).+// min/max stay within the ranges accepted by `drillTypeConfigSchema`.+export const ADAPTIVE_SPECS = {+ 'doubling-chain': { field: 'steps', base: 8, min: 4, max: 16, step: 2, harderIsHigher: true },+ 'serial-subtraction': { field: 'steps', base: 10, min: 5, max: 20, step: 2, harderIsHigher: true },+ 'multiplication': { field: 'maxDigits', base: 2, min: 1, max: 4, step: 1, harderIsHigher: true },+ 'powers': { field: 'maxExponent', base: 10, min: 4, max: 16, step: 2, harderIsHigher: true },+ 'estimation': { field: 'tolerancePct', base: 10, min: 3, max: 20, step: 3, harderIsHigher: false },+};++export const ADAPTIVE_DEFAULTS = {+ highScore: 90, // >= this over enough samples → bump difficulty up one step+ lowScore: 50, // <= this → ease difficulty down one step+ minSamples: 3, // need at least this many scored samples before adapting+ windowDays: 30, // stats window the signal is read over+};++export function clampNum(value, min, max) {+ return Math.min(max, Math.max(min, value));+}++/**+ * Map a recent score to a difficulty direction.+ * @returns {number} 1 = harder, -1 = easier, 0 = hold+ */+export function scoreToDirection(score, { highScore, lowScore } = ADAPTIVE_DEFAULTS) {+ if (score == null || Number.isNaN(score)) return 0;+ if (score >= highScore) return 1;+ if (score <= lowScore) return -1;+ return 0;+}++/**+ * Compute an adapted drill config plus a transparent explanation.+ *+ * @param {string} type - math drill type+ * @param {object} baseConfig - the user's configured drill params+ * @param {{score?: number|null, samples?: number}} signal - recent performance+ * @param {object} [opts] - override ADAPTIVE_DEFAULTS thresholds+ * @returns {{config: object, type, field, from, to, direction, applied, score, samples, reason}}+ */+export function adaptDrillConfig(type, baseConfig = {}, signal = {}, opts = {}) {+ const spec = ADAPTIVE_SPECS[type];+ const options = { ...ADAPTIVE_DEFAULTS, ...opts };+ const base = { ...(baseConfig || {}) };+ const samples = Number.isFinite(signal?.samples) ? signal.samples : 0;+ const score = signal?.score == null || Number.isNaN(signal.score) ? null : signal.score;++ const out = {+ config: base,+ type,+ field: spec?.field ?? null,+ from: null,+ to: null,+ direction: 0,+ applied: false,+ score,+ samples,+ reason: 'unsupported',+ };++ if (!spec) return out;++ const currentRaw = Number.isFinite(base[spec.field]) ? base[spec.field] : spec.base;+ const current = clampNum(currentRaw, spec.min, spec.max);+ out.from = current;+ out.to = current;++ if (samples < options.minSamples) {+ out.reason = 'insufficient-samples';+ return out;+ }++ const direction = scoreToDirection(score, options);+ out.direction = direction;+ if (direction === 0) {+ out.reason = 'hold';+ return out;+ }++ const valueDelta = direction * spec.step * (spec.harderIsHigher ? 1 : -1);+ const next = clampNum(current + valueDelta, spec.min, spec.max);+ out.to = next;++ if (next === current) {+ // Already at the difficulty boundary in the requested direction.+ out.reason = direction > 0 ? 'at-hardest' : 'at-easiest';+ return out;+ }++ out.config = { ...base, [spec.field]: next };+ out.applied = true;+ out.reason = direction > 0 ? 'harder' : 'easier';+ return out;+}diff --git a/server/lib/postAdaptive.test.js b/server/lib/postAdaptive.test.jsnew file mode 100644index 0000000000..f4b87c3d56--- /dev/null+++ b/server/lib/postAdaptive.test.js@@ -0,0 +1,135 @@+import { describe, it, expect } from 'vitest';+import {+ adaptDrillConfig,+ scoreToDirection,+ clampNum,+ ADAPTIVE_SPECS,+ ADAPTIVE_DEFAULTS,+} from './postAdaptive.js';++describe('clampNum', () => {+ it('clamps within bounds', () => {+ expect(clampNum(5, 1, 10)).toBe(5);+ expect(clampNum(-3, 1, 10)).toBe(1);+ expect(clampNum(99, 1, 10)).toBe(10);+ });+});++describe('scoreToDirection', () => {+ it('returns 1 (harder) at/above the high threshold', () => {+ expect(scoreToDirection(90)).toBe(1);+ expect(scoreToDirection(100)).toBe(1);+ });+ it('returns -1 (easier) at/below the low threshold', () => {+ expect(scoreToDirection(50)).toBe(-1);+ expect(scoreToDirection(10)).toBe(-1);+ });+ it('holds in the middle band', () => {+ expect(scoreToDirection(70)).toBe(0);+ expect(scoreToDirection(89)).toBe(0);+ expect(scoreToDirection(51)).toBe(0);+ });+ it('holds on a null/NaN score', () => {+ expect(scoreToDirection(null)).toBe(0);+ expect(scoreToDirection(NaN)).toBe(0);+ });+});++describe('adaptDrillConfig', () => {+ it('leaves non-math / unsupported types untouched', () => {+ const res = adaptDrillConfig('word-association', { count: 5 }, { score: 95, samples: 10 });+ expect(res.applied).toBe(false);+ expect(res.reason).toBe('unsupported');+ expect(res.config).toEqual({ count: 5 });+ });++ it('does not adapt until minSamples is met', () => {+ const res = adaptDrillConfig('multiplication', { maxDigits: 2 }, { score: 99, samples: 2 });+ expect(res.applied).toBe(false);+ expect(res.reason).toBe('insufficient-samples');+ expect(res.config.maxDigits).toBe(2);+ });++ it('bumps the primary knob harder on sustained high scores (higher = harder)', () => {+ const res = adaptDrillConfig('multiplication', { maxDigits: 2 }, { score: 95, samples: 5 });+ expect(res.applied).toBe(true);+ expect(res.reason).toBe('harder');+ expect(res.field).toBe('maxDigits');+ expect(res.from).toBe(2);+ expect(res.to).toBe(3);+ expect(res.config.maxDigits).toBe(3);+ });++ it('eases the primary knob on repeated low scores', () => {+ const res = adaptDrillConfig('doubling-chain', { steps: 8 }, { score: 40, samples: 6 });+ expect(res.applied).toBe(true);+ expect(res.reason).toBe('easier');+ expect(res.from).toBe(8);+ expect(res.to).toBe(6);+ expect(res.config.steps).toBe(6);+ });++ it('holds when performance is in the middle band', () => {+ const res = adaptDrillConfig('powers', { maxExponent: 10 }, { score: 75, samples: 8 });+ expect(res.applied).toBe(false);+ expect(res.reason).toBe('hold');+ expect(res.config.maxExponent).toBe(10);+ });++ it('inverts direction for estimation (lower tolerance is harder)', () => {+ const harder = adaptDrillConfig('estimation', { tolerancePct: 10 }, { score: 95, samples: 5 });+ expect(harder.applied).toBe(true);+ expect(harder.reason).toBe('harder');+ expect(harder.to).toBeLessThan(harder.from); // tightened tolerance++ const easier = adaptDrillConfig('estimation', { tolerancePct: 10 }, { score: 30, samples: 5 });+ expect(easier.applied).toBe(true);+ expect(easier.reason).toBe('easier');+ expect(easier.to).toBeGreaterThan(easier.from); // widened tolerance+ });++ it('never exceeds the spec max when already at the ceiling', () => {+ const spec = ADAPTIVE_SPECS.multiplication;+ const res = adaptDrillConfig('multiplication', { maxDigits: spec.max }, { score: 100, samples: 20 });+ expect(res.applied).toBe(false);+ expect(res.reason).toBe('at-hardest');+ expect(res.config.maxDigits).toBe(spec.max);+ });++ it('never drops below the spec min when already at the floor', () => {+ const spec = ADAPTIVE_SPECS['doubling-chain'];+ const res = adaptDrillConfig('doubling-chain', { steps: spec.min }, { score: 0, samples: 20 });+ expect(res.applied).toBe(false);+ expect(res.reason).toBe('at-easiest');+ expect(res.config.steps).toBe(spec.min);+ });++ it('falls back to the spec base when the config omits the knob', () => {+ const spec = ADAPTIVE_SPECS.multiplication;+ const res = adaptDrillConfig('multiplication', {}, { score: 95, samples: 5 });+ expect(res.from).toBe(spec.base);+ expect(res.to).toBe(clampNum(spec.base + spec.step, spec.min, spec.max));+ });++ it('respects overridden thresholds', () => {+ const res = adaptDrillConfig(+ 'multiplication',+ { maxDigits: 2 },+ { score: 80, samples: 5 },+ { highScore: 75 }+ );+ expect(res.applied).toBe(true);+ expect(res.reason).toBe('harder');+ });++ it('does not mutate the input config object', () => {+ const base = { maxDigits: 2 };+ adaptDrillConfig('multiplication', base, { score: 95, samples: 5 });+ expect(base).toEqual({ maxDigits: 2 });+ });++ it('exposes sane defaults', () => {+ expect(ADAPTIVE_DEFAULTS.highScore).toBeGreaterThan(ADAPTIVE_DEFAULTS.lowScore);+ expect(ADAPTIVE_DEFAULTS.minSamples).toBeGreaterThanOrEqual(1);+ });+});diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex fdbcc92bff..c76d73c5fb 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -110,6 +110,12 @@ export const postConfigUpdateSchema = z.object({sessionModules: z.array(z.string()).optional(),scoring: z.object({weights: z.record(z.number().min(0).max(1)).optional()+ }).optional(),+ // Opt-in adaptive difficulty: when enabled, math drill params are nudged at+ // generation time from recent scored performance (server/lib/postAdaptive.js).+ // Default OFF so existing installs are unchanged — additive, no migration.+ adaptive: z.object({+ enabled: z.boolean().optional()}).optional()}).partial();diff --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.jsindex e487bb4e25..8ebf6cf3e6 100644--- a/server/lib/postValidation.test.js+++ b/server/lib/postValidation.test.js@@ -21,6 +21,13 @@ describe('postConfigUpdateSchema llmDrills', () => {llmDrills: { drillTypes: { 'not-a-drill': { enabled: true } } }})).toThrow();});++ it('accepts the opt-in adaptive difficulty toggle', () => {+ expect(postConfigUpdateSchema.parse({ adaptive: { enabled: true } }).adaptive).toEqual({ enabled: true });+ expect(postConfigUpdateSchema.parse({ adaptive: { enabled: false } }).adaptive).toEqual({ enabled: false });+ // Additive + optional — a config with no adaptive key stays valid.+ expect(postConfigUpdateSchema.parse({}).adaptive).toBeUndefined();+ });});describe('postLlmScoreRequestSchema', () => {diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.jsindex 867ffa9ba4..23ebe5645a 100644--- a/server/routes/meatspacePostRoutes.js+++ b/server/routes/meatspacePostRoutes.js@@ -132,13 +132,28 @@ router.post('/post/drill', asyncHandler(async (req, res) => {return res.json(drill);}- const drill = postService.generateDrill(data.type, data.config);+ // 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 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;res.json(drill);}));+/**+ * GET /api/meatspace/post/adaptive-preview+ * Transparent per-type preview of effective adaptive difficulty for math drills,+ * so the config UI can show what Adaptive will do before a session starts.+ */+router.get('/post/adaptive-preview', asyncHandler(async (req, res) => {+ const preview = await postService.getAdaptivePreview();+ res.json(preview);+}));+/*** POST /api/meatspace/post/score-llm* Score an LLM drill's responses using AI evaluation.diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex 0ebee2326d..001a63322d 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -10,6 +10,7 @@ import { randomUUID } from 'crypto';import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';import { deepMerge, isPlainObject } from '../lib/objects.js';import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES } from '../lib/postValidation.js';+import { adaptDrillConfig, ADAPTIVE_SPECS, ADAPTIVE_DEFAULTS } from '../lib/postAdaptive.js';const MEATSPACE_DIR = PATHS.meatspace;const SESSIONS_FILE = join(MEATSPACE_DIR, 'post-sessions.json');@@ -39,9 +40,16 @@ const DEFAULT_CONFIG = {}},sessionModules: ['mental-math'],- scoring: { weights: { 'mental-math': 1.0, 'llm-drills': 1.0 } }+ scoring: { weights: { 'mental-math': 1.0, 'llm-drills': 1.0 } },+ // Opt-in adaptive difficulty (default OFF). When enabled, math drills are+ // nudged harder/easier at generation time from recent scored performance.+ adaptive: { enabled: false }};+// Math tasks are logged under this coarse module in scored sessions, so the+// adaptive signal reads `byDrill['mental-math:<type>']`.+const MATH_MODULE = 'mental-math';+async function ensureMeatspaceDir() {await ensureDir(MEATSPACE_DIR);}@@ -214,7 +222,7 @@ export async function getPostStats(days = 30) {}if (recent.length === 0) {- return { days, sessionCount: 0, overall: null, byModule: {}, byDrill: {}, ...streaks };+ return { days, sessionCount: 0, overall: null, byModule: {}, byDrill: {}, byDrillCount: {}, ...streaks };}const scores = recent.map(s => s.score);@@ -235,9 +243,13 @@ export async function getPostStats(days = 30) {const avg = arr => Math.round(arr.reduce((a, b) => a + b, 0) / arr.length);for (const key of Object.keys(byModule)) byModule[key] = avg(byModule[key]);+ // byDrillCount is the per-drill sample size, used to gate adaptive difficulty+ // (don't adapt off a single lucky/unlucky run). Captured before averaging.+ const byDrillCount = {};+ for (const key of Object.keys(byDrill)) byDrillCount[key] = byDrill[key].length;for (const key of Object.keys(byDrill)) byDrill[key] = avg(byDrill[key]);- return { days, sessionCount: recent.length, overall, byModule, byDrill, ...streaks };+ return { days, sessionCount: recent.length, overall, byModule, byDrill, byDrillCount, ...streaks };}// =============================================================================@@ -339,6 +351,67 @@ export function generateDrill(type, config = {}) {}}+// =============================================================================+// ADAPTIVE DIFFICULTY+// =============================================================================++/**+ * Read the recent performance signal for one math drill type from scored+ * sessions. Returns { score, samples } — score is the avg session score (0-100)+ * over the adaptive window; samples is how many task samples backed it.+ */+async function getAdaptiveSignal(type) {+ const stats = await getPostStats(ADAPTIVE_DEFAULTS.windowDays);+ const key = `${MATH_MODULE}:${type}`;+ const score = stats.byDrill?.[key];+ const samples = stats.byDrillCount?.[key] || 0;+ return { score: score == null ? null : score, samples };+}++/**+ * 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.+ *+ * @returns {{ config: object, adaptive: object|null }}+ */+export async function resolveDrillConfig(type, requestedConfig = {}) {+ const config = await getPostConfig();+ if (!config?.adaptive?.enabled || !ADAPTIVE_SPECS[type]) {+ return { config: requestedConfig, adaptive: null };+ }+ const signal = await getAdaptiveSignal(type);+ const result = adaptDrillConfig(type, requestedConfig, signal);+ return { config: result.config, adaptive: result };+}++/**+ * Build a transparent per-type preview of the effective adaptive difficulty for+ * every supported math drill, so the config UI can show what Adaptive will do+ * before a session starts. `enabled` reflects the saved Adaptive toggle.+ */+export async function getAdaptivePreview() {+ const config = await getPostConfig();+ const enabled = !!config?.adaptive?.enabled;+ const stats = await getPostStats(ADAPTIVE_DEFAULTS.windowDays);+ const savedDrills = config?.mentalMath?.drillTypes || {};++ const drills = {};+ for (const type of Object.keys(ADAPTIVE_SPECS)) {+ const key = `${MATH_MODULE}:${type}`;+ const signal = {+ score: stats.byDrill?.[key] == null ? null : stats.byDrill[key],+ samples: stats.byDrillCount?.[key] || 0,+ };+ // Base off the user's saved config so the preview matches what a session+ // would actually use; adaptDrillConfig falls back to the spec base per field.+ drills[type] = adaptDrillConfig(type, savedDrills[type] || {}, signal);+ }++ return { enabled, windowDays: ADAPTIVE_DEFAULTS.windowDays, thresholds: { highScore: ADAPTIVE_DEFAULTS.highScore, lowScore: ADAPTIVE_DEFAULTS.lowScore, minSamples: ADAPTIVE_DEFAULTS.minSamples }, drills };+}+// =============================================================================// SCORING (pure functions)// =============================================================================