Skip to content

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

feat([issue-3252]): add a Practice Plan surface backed by an enumerable POST topic registry

[._.]/ Adam Eivye0830bb748ad
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0226455b65..8bba3b1f28 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,11 @@
## POST
+- **[issue-3252] A new Practice Plan page decides what you're actually studying.** POST had grown to roughly thirty drill types across six subjects plus three standalone study surfaces, with no single place to say which of them you want. Practice Plan (`/post/plan`, also reachable from ⌘K and by voice) lists every topic with a switch, expandable to its individual drills, and shows a live "your daily POST will include…" summary that updates as you flip switches — so you can see what tomorrow's session becomes before you run it. Drill Config still owns how hard each drill is; Practice Plan owns what's in the rotation.
+- **[issue-3252] "Wordplay only" is now one switch instead of eight.** Wordplay, Verbal Agility and Imagination all used to hide behind a single "Wit & Memory (AI)" checkbox, so keeping just one of them meant unchecking eight individual drill types by hand — and the subjects the launcher showed you weren't the ones the settings page let you edit. Each is now its own topic, and switching one off drops its drills from Full and Quick sessions and from the "Up next" recommendations together.
+- **[issue-3252] Memorized texts can leave the daily rotation without being deleted.** Not wanting the built-in Elements Song in your reviews used to mean deleting it, which threw away every bit of mastery and scheduling history you'd built up. Each memorized text now has its own switch: switch one off and it stops being recommended and stops being auto-picked for memory drills, but keeps all its history and stays available to practise any time from its own page.
+- **[issue-3252] Morse can be switched off if you're not learning CW.** The launcher used to suggest "Morse: keep climbing" indefinitely with no way to decline. Morse is now a topic like any other, and switching it off stops those suggestions.
+
- **[issue-3249] The POST launcher now opens on what to do, not on what you've done.** Starting a session meant scrolling past Today's Status, Goals, Up next, the streak and trend cards, the mode toggle and the Conditions form to reach "Quick 5 Min" and "Full POST" at the very bottom of the page. Those actions are now the first thing on the launcher, on a single Start card that also carries a one-click CTA for whatever is recommended next — the exact drill you're weakest at, a due maintenance rep, or the memory item that came due — plus the Test/Train toggle. The optional Conditions fields are tucked behind a disclosure that remembers what you typed and shows a count when collapsed, so they can't push the buttons out of view again.
- **[issue-3249] "Up next" recommendations now start the practice instead of dropping you on a page.** A due memory item like *Review "The Elements Song"* used to link at the memory list, where you still had to find the item, open it, scroll past the periodic table, and pick one of five practice modes — four clicks and two scrolls to reach an actual drill. It's now one click straight into a running drill: the Elements Song opens its recall test, and any other memory item opens spaced repetition, which targets its weakest verses.
- **[issue-3249] Every memory practice mode now has its own link.** Practising a memory item is addressable — `/post/memory/<item>/spaced`, `/post/memory/elements/element-flash` — so a drill can be bookmarked, shared, reopened after a reload, and reached from ⌘K or by voice, the same way the Morse modes already work. Browser Back now steps out of a drill to the mode list and then to your items, and the Elements Song modes (Flash Cards, Element Flash, Fill the Lyrics, Learn Lyrics) are each individually reachable from the command palette.
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index a635f17dee..4b9322ac2d 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -350,6 +350,7 @@ const navItems = [
{ to: '/post/launcher', label: 'Launcher', icon: Play },
{ to: '/post/memory', label: 'Memory', icon: Brain },
{ to: '/post/morse', label: 'Morse', icon: Radio },
+ { to: '/post/plan', label: 'Practice Plan', icon: ListChecks },
{ to: '/post/progress', label: 'Progress', icon: TrendingUp },
{ to: '/post/wordplay', label: 'Wordplay', icon: MessageCircle },
],
diff --git a/client/src/components/meatspace/post/PostDrillConfig.jsx b/client/src/components/meatspace/post/PostDrillConfig.jsx
index 7e1f405215..05ef77c529 100644
--- a/client/src/components/meatspace/post/PostDrillConfig.jsx
+++ b/client/src/components/meatspace/post/PostDrillConfig.jsx
@@ -4,16 +4,26 @@ import { updatePostConfig, getProviders, getPostAdaptivePreview, getPostMultipli
import toast from '../../ui/Toast';
import { FormField } from '../../ui/FormField';
import { filterSelectableModels, enabledApiProviderFilter } from '../../../utils/providers';
-import { GOAL_DEFS } from './constants';
+import { GOAL_DEFS, POST_TOPICS } from './constants';
-// Modules a Full/Quick composed session can draw from (issue #2100). Memory is
-// deliberately absent — it has no launcher-composed drill yet (practice lives in
-// the Memory tab), so offering it here would let a user build an empty session.
-const SESSION_MODULE_OPTIONS = [
- { id: 'mental-math', label: 'Mental Math' },
- { id: 'cognitive', label: 'Cognitive' },
- { id: 'llm-drills', label: 'Wit & Memory (AI)' },
-];
+// Modules a Full/Quick composed session can draw from (issue #2100), DERIVED
+// from the shared topic registry so the list has one owner (issue #3252): a
+// module is offered exactly when some topic composes into a session
+// (`surface: 'session'`). That keeps `memory` and `morse` out — both are
+// standalone surfaces with no launcher-composed drill, so offering them here
+// would only let a user build an empty session. Their participation is
+// controlled from the Practice Plan instead.
+const MODULE_LABEL_OVERRIDES = { 'llm-drills': 'Wit & Memory (AI)' };
+const SESSION_MODULE_OPTIONS = POST_TOPICS
+ .filter(t => t.surface === 'session' && t.module)
+ .reduce((out, t) => {
+ if (out.some(o => o.id === t.module)) return out;
+ // One row per MODULE, not per topic — several topics (wordplay / verbal /
+ // imagination) share `llm-drills`, so the first topic's label would be
+ // misleading; the override names the module.
+ out.push({ id: t.module, label: MODULE_LABEL_OVERRIDES[t.module] || t.label });
+ return out;
+ }, []);
// Human labels for the adaptive difficulty knob each math drill tunes.
const ADAPTIVE_FIELD_LABELS = {
diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsx
index bd42c75a1e..3979c77038 100644
--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx
+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx
@@ -4,7 +4,7 @@ import { Zap, History, Settings, Play, Brain, BookOpen, Dumbbell, Timer, Radio,
import { getProviders, getPostReviewReps, getPostRecommendations, getMorseProgress, getPostProgress } from '../../../services/api';
import { FormField } from '../../ui/FormField';
import { isApiProvider } from '../../../utils/providers';
-import { DOMAINS, DRILL_TO_DOMAIN, DRILL_LABELS, computeDomainAverages, computeGoalProgress } from './constants';
+import { DOMAINS, DRILL_TO_DOMAIN, DRILL_LABELS, computeDomainAverages, computeGoalProgress, isTopicEnabled, resolveTopicForDrillType } from './constants';
import { streakGlyph } from '../../../lib/streakGlyph.js';
import useUserTimezone from '../../../hooks/useUserTimezone.js';
import { todayKeyInTimezone } from '../../../utils/timezone.js';
@@ -144,11 +144,19 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
const todaySession = recentSessions?.find(s => s.date === today);
const lastThree = (recentSessions || []).slice(-3).reverse();
+ // Practice-topic gate (issue #3252). Applied at the SOURCE of every enabled-
+ // drill list so a switched-off topic disappears from composed sessions, Quick
+ // sessions, domain-focus practice, and the "Up next" actions alike — that's
+ // what makes "only Wordplay" a single toggle instead of unchecking eight
+ // individual LLM drill types. A drill type with no registry entry has no topic
+ // and is never gated.
+ const topicAllowed = (type) => isTopicEnabled(config, resolveTopicForDrillType(type)?.id);
+
const enabledMathDrills = Object.entries(config.mentalMath?.drillTypes || {})
- .filter(([, cfg]) => cfg.enabled);
+ .filter(([type, cfg]) => cfg.enabled && topicAllowed(type));
const enabledLlmDrills = config.llmDrills?.enabled !== false
- ? Object.entries(config.llmDrills?.drillTypes || {}).filter(([, cfg]) => cfg.enabled !== false)
+ ? Object.entries(config.llmDrills?.drillTypes || {}).filter(([type, cfg]) => cfg.enabled !== false && topicAllowed(type))
: [];
const llmProviderId = config.llmDrills?.providerId || null;
@@ -156,7 +164,7 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
// Deterministic cognitive drills (n-back / digit-span / stroop). No provider.
const enabledCognitiveDrills = config.cognitive?.enabled !== false
- ? Object.entries(config.cognitive?.drillTypes || {}).filter(([, cfg]) => cfg.enabled !== false)
+ ? Object.entries(config.cognitive?.drillTypes || {}).filter(([type, cfg]) => cfg.enabled !== false && topicAllowed(type))
: [];
// Only the fields each cognitive generator reads; extras are harmless.
diff --git a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx b/client/src/components/meatspace/post/PostSessionLauncher.test.jsx
index 55640c9638..1b09057343 100644
--- a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx
+++ b/client/src/components/meatspace/post/PostSessionLauncher.test.jsx
@@ -406,3 +406,91 @@ describe('PostSessionLauncher — Start card (issue #3249)', () => {
expect(screen.getByPlaceholderText('good/poor').value).toBe('poor');
});
});
+
+// Practice-topic gating (issue #3252). The four fine-grained domains that
+// collapse into the single `llm-drills` module could not be separated by the
+// coarse sessionModules filter — "Wordplay only" meant unchecking eight drill
+// types by hand. A topic toggle now does it in one move.
+describe('PostSessionLauncher topic gating (issue #3252)', () => {
+ const llmConfig = (topics) => ({
+ mentalMath: { enabled: true, drillTypes: {} },
+ llmDrills: {
+ enabled: true,
+ drillTypes: {
+ 'pun-wordplay': { enabled: true, count: 5 },
+ 'bridge-word': { enabled: true, count: 5 },
+ 'wit-comeback': { enabled: true, count: 5 },
+ 'what-if': { enabled: true, count: 5 },
+ },
+ },
+ cognitive: { enabled: false, drillTypes: {} },
+ sessionModules: ['llm-drills'],
+ ...(topics ? { topics } : {}),
+ });
+
+ const renderWith = (config, onStart) => render(
+ <MemoryRouter>
+ <PostSessionLauncher
+ config={config}
+ recentSessions={[]}
+ stats={{ sessionCount: 1, overall: 70, currentStreak: 1, longestStreak: 1, byDrill: {} }}
+ statsWeek={{ sessionCount: 1 }}
+ onStart={onStart}
+ onViewHistory={vi.fn()}
+ onViewConfig={vi.fn()}
+ onViewMemory={vi.fn()}
+ onViewMorse={vi.fn()}
+ />
+ </MemoryRouter>,
+ );
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getPostRecommendations.mockResolvedValue({ recommendations: [] });
+ getPostReviewReps.mockResolvedValue({ reps: [] });
+ getMorseProgress.mockResolvedValue({ settings: { wpm: 18, farnsworthWpm: 12 } });
+ getPostProgress.mockResolvedValue({ series: { byDay: [] } });
+ });
+
+ it('composes every llm-drills topic when no topics key is set (legacy config)', async () => {
+ const onStart = vi.fn();
+ renderWith(llmConfig(null), onStart);
+ await waitFor(() => expect(screen.getByText('Full POST')).toBeTruthy());
+ fireEvent.click(screen.getByText('Full POST'));
+
+ const types = onStart.mock.calls[0][0].map(d => d.type).sort();
+ expect(types).toEqual(['bridge-word', 'pun-wordplay', 'what-if', 'wit-comeback']);
+ });
+
+ it('composes ONLY wordplay drills when the sibling llm topics are switched off', async () => {
+ const onStart = vi.fn();
+ renderWith(llmConfig({ verbal: { enabled: false }, imagination: { enabled: false } }), onStart);
+ await waitFor(() => expect(screen.getByText('Full POST')).toBeTruthy());
+ fireEvent.click(screen.getByText('Full POST'));
+
+ const types = onStart.mock.calls[0][0].map(d => d.type).sort();
+ expect(types).toEqual(['bridge-word', 'pun-wordplay']);
+ });
+
+ it('a disabled topic is excluded from Quick sessions too, not just Full POST', async () => {
+ const onStart = vi.fn();
+ // The Quick button only renders with ≥2 composable domains, so keep math in
+ // alongside wordplay while verbal/imagination are switched off.
+ renderWith({
+ ...llmConfig({ verbal: { enabled: false }, imagination: { enabled: false } }),
+ mentalMath: { enabled: true, drillTypes: { multiplication: { enabled: true, count: 10 } } },
+ sessionModules: ['mental-math', 'llm-drills'],
+ }, onStart);
+ // The label interpolates the domain count, so it spans multiple text nodes
+ // — query the button by accessible name, not by a text node.
+ const quick = await screen.findByRole('button', { name: /Quick 5 Min/ });
+ fireEvent.click(quick);
+
+ for (const drill of onStart.mock.calls[0][0]) {
+ expect(['pun-wordplay', 'bridge-word', 'multiplication']).toContain(drill.type);
+ }
+ // Quick picks one drill per domain — math and wordplay only, never the two
+ // switched-off llm topics.
+ expect(onStart.mock.calls[0][0].map(d => d.domain).sort()).toEqual(['math', 'wordplay']);
+ });
+});
diff --git a/client/src/components/meatspace/post/PracticePlan.jsx b/client/src/components/meatspace/post/PracticePlan.jsx
new file mode 100644
index 0000000000..f60a05bf78
--- /dev/null
+++ b/client/src/components/meatspace/post/PracticePlan.jsx
@@ -0,0 +1,313 @@
+import { useState, useEffect } from 'react';
+import { ArrowLeft, Save, ChevronRight, ChevronDown, ListChecks, Loader } from 'lucide-react';
+import { updatePostConfig, getMemoryItems } from '../../../services/api';
+import toast from '../../ui/Toast';
+import {
+ POST_TOPICS,
+ TOPIC_UI,
+ DRILL_LABELS,
+ MODULE_CONFIG_KEY,
+ isTopicEnabled,
+ isMemoryItemEnabled,
+ composedSessionDrillTypes,
+} from './constants';
+
+// The one place the user answers "what am I actually studying?" (issue #3252).
+// Practice Plan owns the WHAT (which topics, drill types, and memorized texts
+// participate); Drill Config still owns the HOW HARD (per-drill knobs).
+
+// Coarse module → the heading topics are grouped under. Morse has a null module
+// (it never posts a scored POST task) and lands in its own group.
+const MODULE_GROUPS = [
+ { module: 'mental-math', label: 'Mental Math' },
+ { module: 'llm-drills', label: 'Wit & Language (AI)' },
+ { module: 'cognitive', label: 'Cognitive' },
+ { module: 'memory', label: 'Memory' },
+ { module: null, label: 'Other Practice' },
+];
+
+const drillLabel = (type) => DRILL_LABELS[type] || type;
+
+// A single on/off row. Kept local (rather than reaching for a shared control)
+// so the parent/child indentation and the disabled-parent cascade read in one
+// place. `id` pairs the label with its input per the client label convention.
+function ToggleRow({ id, label, hint, checked, disabled, onChange, indent = false }) {
+ // The hint sits OUTSIDE the <label> and is wired with aria-describedby: inside
+ // it, it would become part of the control's accessible name ("Morse Practiced
+ // from its own tab") instead of supplementary description.
+ const hintId = hint ? `${id}-hint` : undefined;
+ return (
+ <div className={`flex items-start justify-between gap-3 py-1.5 ${indent ? 'pl-7' : ''}`}>
+ <div className="min-w-0">
+ <label htmlFor={id} className={`text-sm ${disabled ? 'text-gray-600' : 'text-gray-300'} cursor-pointer`}>
+ {label}
+ </label>
+ {hint && <p id={hintId} className="text-xs text-gray-500">{hint}</p>}
+ </div>
+ <input
+ id={id}
+ type="checkbox"
+ checked={checked}
+ disabled={disabled}
+ aria-describedby={hintId}
+ onChange={(e) => onChange(e.target.checked)}
+ className="mt-0.5 w-4 h-4 shrink-0 accent-port-accent disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
+ />
+ </div>
+ );
+}
+
+export default function PracticePlan({ config, onSaved, onBack }) {
+ // Draft state seeded once from the loaded config — mirrors PostDrillConfig,
+ // which is why PostTab only mounts this after the config resolves.
+ const [topics, setTopics] = useState(() => ({ ...(config?.topics || {}) }));
+ // Seeded with an entry for EVERY drill type the module owns, because the
+ // config schema's enum-keyed drill-type records are exhaustive (zod 4) — a
+ // partial map would 400 on save. A type absent from the saved config is
+ // seeded `enabled: false`, which is exactly how the launcher already treats
+ // it (it enumerates persisted keys only), so seeding changes nothing about
+ // which drills actually run.
+ const [modules, setModules] = useState(() => Object.fromEntries(
+ Object.entries(MODULE_CONFIG_KEY).map(([module, key]) => {
+ const saved = config?.[key]?.drillTypes || {};
+ const owned = POST_TOPICS.filter(t => t.module === module).flatMap(t => t.drillTypes);
+ return [key, {
+ enabled: config?.[key]?.enabled !== false,
+ drillTypes: Object.fromEntries(owned.map(type => [type, saved[type] || { enabled: false }])),
+ }];
+ })
+ ));
+ const [memoryItemFlags, setMemoryItemFlags] = useState(() => ({ ...(config?.memory?.items || {}) }));
+ const [memoryItems, setMemoryItems] = useState(null);
+ const [expanded, setExpanded] = useState({});
+ const [saving, setSaving] = useState(false);
+
+ useEffect(() => {
+ // Silent: the plan still renders (and saves) without the item list; only the
+ // per-item rows are missing, and an error toast here would be noise.
+ getMemoryItems({ silent: true }).then(setMemoryItems).catch(() => setMemoryItems([]));
+ }, []);
+
+ // Memory and Morse each have a module-level `enabled` flag on the server AND a
+ // topic entry. The user gets ONE control — the topic toggle — and save writes
+ // both, so the server's two gates can never disagree.
+ const memoryOn = isTopicEnabled({ topics }, 'memory');
+ const morseOn = isTopicEnabled({ topics }, 'morse');
+
+ // The draft config the preview reads, so the "will include" summary reflects
+ // unsaved edits — the whole point of the surface is seeing the effect BEFORE
+ // running a session.
+ const draftConfig = {
+ ...config,
+ ...Object.fromEntries(Object.entries(modules).map(([key, v]) => [key, { ...config?.[key], ...v }])),
+ topics,
+ morse: { enabled: morseOn },
+ memory: { ...config?.memory, ...modules.memory, enabled: memoryOn, items: memoryItemFlags },
+ };
+
+ const preview = composedSessionDrillTypes(draftConfig);
+ const previewTopicIds = Object.keys(preview);
+
+ // Standalone topics still shape the daily rotation (they drive "Up next"
+ // recommendations) even though they never compose into a session.
+ const standaloneOn = POST_TOPICS
+ .filter(t => t.surface === 'standalone' && isTopicEnabled(draftConfig, t.id));
+
+ const enabledMemoryItems = (memoryItems || [])
+ .filter(item => isMemoryItemEnabled(draftConfig, item.id));
+
+ function setTopicEnabled(topicId, enabled) {
+ setTopics(prev => ({ ...prev, [topicId]: { ...prev[topicId], enabled } }));
+ }
+
+ function setDrillEnabled(module, type, enabled) {
+ const key = MODULE_CONFIG_KEY[module];
+ if (!key) return;
+ setModules(prev => ({
+ ...prev,
+ [key]: { ...prev[key], drillTypes: { ...prev[key].drillTypes, [type]: { ...prev[key].drillTypes[type], enabled } } },
+ }));
+ }
+
+ function setMemoryItemEnabled(itemId, enabled) {
+ setMemoryItemFlags(prev => ({ ...prev, [itemId]: { ...prev[itemId], enabled } }));
+ }
+
+ async function handleSave() {
+ setSaving(true);
+ // Only the slices this surface owns are sent — Drill Config's knobs live in
+ // the same `drillTypes` objects and are carried through untouched because
+ // the draft was seeded from the saved config and the server deep-merges.
+ const updated = await updatePostConfig({
+ topics,
+ mentalMath: { drillTypes: modules.mentalMath.drillTypes },
+ llmDrills: { drillTypes: modules.llmDrills.drillTypes },
+ cognitive: { drillTypes: modules.cognitive.drillTypes },
+ memory: { enabled: memoryOn, drillTypes: modules.memory.drillTypes, items: memoryItemFlags },
+ morse: { enabled: morseOn },
+ }, { silent: true }).catch(() => null);
+ setSaving(false);
+ if (!updated) {
+ toast.error('Could not save your practice plan');
+ return;
+ }
+ toast.success('Practice plan saved');
+ onSaved?.(updated);
+ }
+
+ function renderTopic(topic) {
+ const on = isTopicEnabled({ topics }, topic.id);
+ const isOpen = !!expanded[topic.id];
+ const ui = TOPIC_UI[topic.id] || {};
+ const configKey = MODULE_CONFIG_KEY[topic.module];
+ const isMemory = topic.id === 'memory';
+ const isMorse = topic.id === 'morse';
+ // Morse's trainer owns its own settings, so the topic toggle is the whole
+ // control — there are no per-drill-type rows to expand into.
+ const hasChildren = !isMorse;
+
+ return (
+ <div key={topic.id} className="p-3 bg-port-card border border-port-border rounded-lg">
+ <div className="flex items-center gap-2">
+ {hasChildren ? (
+ <button
+ type="button"
+ aria-label={`${isOpen ? 'Collapse' : 'Expand'} ${topic.label}`}
+ aria-expanded={isOpen}
+ onClick={() => setExpanded(prev => ({ ...prev, [topic.id]: !prev[topic.id] }))}
+ className="text-gray-500 hover:text-white transition-colors"
+ >
+ {isOpen ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
+ </button>
+ ) : (
+ <span className="w-4" />
+ )}
+ <div className="flex-1">
+ <ToggleRow
+ id={`topic-${topic.id}`}
+ label={<span className={`font-medium ${on ? ui.color || 'text-white' : 'text-gray-500'}`}>{topic.label}</span>}
+ hint={topic.surface === 'standalone' ? 'Practiced from its own tab' : null}
+ checked={on}
+ onChange={(v) => setTopicEnabled(topic.id, v)}
+ />
+ </div>
+ </div>
+
+ {isOpen && (
+ <div className="mt-1 border-t border-port-border/60 pt-2">
+ {isMorse ? null : topic.drillTypes.map(type => (
+ <ToggleRow
+ key={type}
+ indent
+ id={`drill-${type}`}
+ label={drillLabel(type)}
+ checked={on && (modules[configKey]?.drillTypes?.[type]?.enabled !== false)}
+ // A disabled parent disables everything under it — shown as
+ // greyed-out rather than hidden, so the state stays legible.
+ disabled={!on}
+ onChange={(v) => setDrillEnabled(topic.module, type, v)}
+ />
+ ))}
+
+ {isMemory && (
+ <div className="mt-2 border-t border-port-border/60 pt-2">
+ <p className="pl-7 text-xs uppercase tracking-wider text-gray-500 mb-1">Memorized texts</p>
+ {memoryItems === null && (
+ <p className="pl-7 text-xs text-gray-500 flex items-center gap-1.5">
+ <Loader size={12} className="animate-spin" /> Loading your items…
+ </p>
+ )}
+ {memoryItems?.length === 0 && (
+ <p className="pl-7 text-xs text-gray-500">No memory items yet — add one from the Memory tab.</p>
+ )}
+ {(memoryItems || []).map(item => (
+ <ToggleRow
+ key={item.id}
+ indent
+ id={`memory-item-${item.id}`}
+ label={item.title || item.id}
+ hint="Switching off keeps its history and its own practice page"
+ checked={on && (memoryItemFlags[item.id]?.enabled !== false)}
+ disabled={!on}
+ onChange={(v) => setMemoryItemEnabled(item.id, v)}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-3">
+ <button aria-label="Back" onClick={onBack} className="text-gray-400 hover:text-white transition-colors">
+ <ArrowLeft size={20} />
+ </button>
+ <div>
+ <h2 className="text-xl font-bold text-white">Practice Plan</h2>
+ <p className="text-xs text-gray-500">What you're studying. Difficulty knobs live in Config.</p>
+ </div>
+ </div>
+ <button
+ onClick={handleSave}
+ disabled={saving}
+ className="flex items-center gap-1.5 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white text-sm font-medium rounded-lg transition-colors"
+ >
+ <Save size={14} />
+ {saving ? 'Saving...' : 'Save'}
+ </button>
+ </div>
+
+ {/* Live summary — reflects UNSAVED edits so the effect of a toggle is
+ visible before running a session. */}
+ <div data-testid="plan-summary" className="p-4 bg-port-card border border-port-border rounded-lg">
+ <div className="flex items-center gap-2 mb-2">
+ <ListChecks size={16} className="text-port-accent" />
+ <h3 className="text-sm font-semibold text-white">Your daily POST will include</h3>
+ </div>
+ {previewTopicIds.length === 0 ? (
+ <p className="text-sm text-gray-500">
+ Nothing right now — every session topic is switched off, or excluded by Session Composition in Config.
+ </p>
+ ) : (
+ <ul className="space-y-1">
+ {previewTopicIds.map(id => (
+ <li key={id} className="text-sm">
+ <span className={`font-medium ${TOPIC_UI[id]?.color || 'text-white'}`}>
+ {POST_TOPICS.find(t => t.id === id)?.label}
+ </span>
+ <span className="text-gray-400"> — {preview[id].map(drillLabel).join(', ')}</span>
+ </li>
+ ))}
+ </ul>
+ )}
+ {standaloneOn.length > 0 && (
+ <p className="mt-3 pt-3 border-t border-port-border/60 text-xs text-gray-400">
+ Also in your rotation (practiced from their own tabs):{' '}
+ <span className="text-gray-300">{standaloneOn.map(t => t.label).join(', ')}</span>
+ {memoryItems?.length > 0 && standaloneOn.some(t => t.id === 'memory') && (
+ <span className="text-gray-500">
+ {' '}· {enabledMemoryItems.length} of {memoryItems.length} memorized text{memoryItems.length === 1 ? '' : 's'}
+ </span>
+ )}
+ </p>
+ )}
+ </div>
+
+ {MODULE_GROUPS.map(group => {
+ const groupTopics = POST_TOPICS.filter(t => t.module === group.module);
+ if (!groupTopics.length) return null;
+ return (
+ <div key={group.label} className="space-y-2">
+ <h3 className="text-xs uppercase tracking-wider text-gray-500">{group.label}</h3>
+ {groupTopics.map(renderTopic)}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/client/src/components/meatspace/post/PracticePlan.test.jsx b/client/src/components/meatspace/post/PracticePlan.test.jsx
new file mode 100644
index 0000000000..f80c3d558f
--- /dev/null
+++ b/client/src/components/meatspace/post/PracticePlan.test.jsx
@@ -0,0 +1,200 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor, fireEvent, within, act } from '@testing-library/react';
+
+vi.mock('../../../services/api', () => ({
+ updatePostConfig: vi.fn(),
+ getMemoryItems: vi.fn(),
+}));
+
+vi.mock('../../ui/Toast', () => ({
+ default: { success: vi.fn(), error: vi.fn() },
+}));
+
+import PracticePlan from './PracticePlan';
+import { updatePostConfig, getMemoryItems } from '../../../services/api';
+import toast from '../../ui/Toast';
+
+// A config shaped like what the server actually hands the client: DEFAULT_CONFIG
+// deep-merged over whatever is saved. Deliberately carries NO `topics` key, so
+// every test starts from the legacy "absent = enabled" baseline.
+const baseConfig = (overrides = {}) => ({
+ mentalMath: {
+ enabled: true,
+ drillTypes: {
+ 'doubling-chain': { enabled: true },
+ 'serial-subtraction': { enabled: true },
+ multiplication: { enabled: true },
+ powers: { enabled: true },
+ estimation: { enabled: true },
+ },
+ },
+ llmDrills: {
+ enabled: true,
+ drillTypes: {
+ 'pun-wordplay': { enabled: true },
+ 'word-association': { enabled: true },
+ 'wit-comeback': { enabled: true },
+ 'what-if': { enabled: true },
+ },
+ },
+ cognitive: { enabled: true, drillTypes: { 'n-back': { enabled: true } } },
+ memory: { enabled: true, drillTypes: { 'memory-sequence': { enabled: true } } },
+ morse: { enabled: true },
+ // No sessionModules → legacy/absent → every module composes.
+ ...overrides,
+});
+
+const MEMORY_ITEMS = [
+ { id: 'elements-song', title: 'The Elements' },
+ { id: 'raven', title: 'The Raven' },
+];
+
+// Settle the mount-time memory-items fetch inside act() so the strict act()
+// guard in src/test/setup.js doesn't fail the test on a post-mount state update.
+async function renderPlan(config = baseConfig(), props = {}) {
+ const result = render(<PracticePlan config={config} onSaved={() => {}} onBack={() => {}} {...props} />);
+ await act(async () => {});
+ return result;
+}
+
+const summary = () => screen.getByTestId('plan-summary');
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getMemoryItems.mockResolvedValue(MEMORY_ITEMS);
+ updatePostConfig.mockResolvedValue({});
+});
+
+describe('PracticePlan summary (issue #3252)', () => {
+ it('lists every enabled session topic with its drills', async () => {
+ await renderPlan();
+ const box = summary();
+ expect(within(box).getByText('Mental Math')).toBeInTheDocument();
+ expect(within(box).getByText('Wordplay')).toBeInTheDocument();
+ expect(within(box).getByText('Verbal Agility')).toBeInTheDocument();
+ expect(within(box).getByText('Imagination')).toBeInTheDocument();
+ expect(within(box).getByText(/Pun & Wordplay/)).toBeInTheDocument();
+ });
+
+ it('drops a topic from the summary as soon as it is toggled off — before saving', async () => {
+ await renderPlan();
+ expect(within(summary()).getByText('Verbal Agility')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByLabelText('Verbal Agility', { selector: 'input' }));
+
+ await waitFor(() => {
+ expect(within(summary()).queryByText('Verbal Agility')).not.toBeInTheDocument();
+ });
+ // Its sibling llm-drills topic is untouched — that's the granularity the
+ // coarse sessionModules filter could never express.
+ expect(within(summary()).getByText('Wordplay')).toBeInTheDocument();
+ expect(updatePostConfig).not.toHaveBeenCalled();
+ });
+
+ it('leaves only wordplay when every other session topic is switched off', async () => {
+ await renderPlan();
+ for (const label of ['Mental Math', 'Verbal Agility', 'Imagination', 'Cognitive']) {
+ fireEvent.click(screen.getByLabelText(label, { selector: 'input' }));
+ }
+ await waitFor(() => {
+ expect(within(summary()).getByText('Wordplay')).toBeInTheDocument();
+ });
+ for (const label of ['Mental Math', 'Verbal Agility', 'Imagination', 'Cognitive']) {
+ expect(within(summary()).queryByText(label)).not.toBeInTheDocument();
+ }
+ });
+
+ it('explains an empty plan instead of rendering a blank summary', async () => {
+ await renderPlan(baseConfig({ sessionModules: [] }));
+ expect(within(summary()).getByText(/Nothing right now/)).toBeInTheDocument();
+ });
+
+ it('counts the memory items still in the rotation', async () => {
+ await renderPlan();
+ await waitFor(() => expect(getMemoryItems).toHaveBeenCalled());
+ await waitFor(() => {
+ expect(within(summary()).getByText(/2 of 2 memorized texts/)).toBeInTheDocument();
+ });
+ });
+});
+
+describe('PracticePlan per-item memory control', () => {
+ it('lists memory items under the expanded Memory topic and drops a disabled one from the count', async () => {
+ await renderPlan();
+ await waitFor(() => expect(getMemoryItems).toHaveBeenCalled());
+
+ fireEvent.click(screen.getByLabelText('Expand Memory'));
+ const itemToggle = await screen.findByLabelText('The Elements', { selector: 'input' });
+ expect(itemToggle).toBeChecked();
+
+ fireEvent.click(itemToggle);
+ await waitFor(() => {
+ expect(within(summary()).getByText(/1 of 2 memorized texts/)).toBeInTheDocument();
+ });
+ });
+
+ it('greys out (and never silently re-enables) sub-toggles when the parent topic is off', async () => {
+ await renderPlan();
+ await waitFor(() => expect(getMemoryItems).toHaveBeenCalled());
+ fireEvent.click(screen.getByLabelText('Expand Memory'));
+ await screen.findByLabelText('The Raven', { selector: 'input' });
+
+ fireEvent.click(screen.getByLabelText('Memory', { selector: 'input' }));
+
+ await waitFor(() => {
+ expect(screen.getByLabelText('The Raven', { selector: 'input' })).toBeDisabled();
+ });
+ expect(screen.getByLabelText('The Raven', { selector: 'input' })).not.toBeChecked();
+ });
+});
+
+describe('PracticePlan save', () => {
+ it('persists topics, per-item memory flags and the morse toggle in one patch', async () => {
+ const onSaved = vi.fn();
+ updatePostConfig.mockResolvedValue({ ok: true });
+ await renderPlan(baseConfig(), { onSaved });
+ await waitFor(() => expect(getMemoryItems).toHaveBeenCalled());
+
+ fireEvent.click(screen.getByLabelText('Morse', { selector: 'input' }));
+ fireEvent.click(screen.getByLabelText('Imagination', { selector: 'input' }));
+ fireEvent.click(screen.getByLabelText('Expand Memory'));
+ fireEvent.click(await screen.findByLabelText('The Elements', { selector: 'input' }));
+
+ fireEvent.click(screen.getByRole('button', { name: /Save/ }));
+
+ await waitFor(() => expect(updatePostConfig).toHaveBeenCalled());
+ const [patch, options] = updatePostConfig.mock.calls[0];
+ expect(patch.topics.imagination).toEqual({ enabled: false });
+ expect(patch.morse).toEqual({ enabled: false });
+ expect(patch.memory.items['elements-song']).toEqual({ enabled: false });
+ // The component owns its own error toast, so the helper must stay silent.
+ expect(options).toEqual({ silent: true });
+ await waitFor(() => expect(onSaved).toHaveBeenCalledWith({ ok: true }));
+ expect(toast.success).toHaveBeenCalled();
+ });
+
+ it('sends a COMPLETE drill-type map per module — the config schema records are exhaustive', async () => {
+ await renderPlan();
+ fireEvent.click(screen.getByRole('button', { name: /Save/ }));
+
+ await waitFor(() => expect(updatePostConfig).toHaveBeenCalled());
+ const [patch] = updatePostConfig.mock.calls[0];
+ expect(Object.keys(patch.llmDrills.drillTypes)).toHaveLength(14);
+ expect(Object.keys(patch.mentalMath.drillTypes)).toHaveLength(5);
+ expect(Object.keys(patch.cognitive.drillTypes)).toHaveLength(6);
+ expect(Object.keys(patch.memory.drillTypes)).toHaveLength(3);
+ // A drill type absent from the saved config is persisted as disabled — the
+ // launcher already ignored it, so seeding must not silently switch it on.
+ expect(patch.llmDrills.drillTypes['bridge-word']).toEqual({ enabled: false });
+ expect(patch.llmDrills.drillTypes['pun-wordplay']).toEqual({ enabled: true });
+ });
+
+ it('surfaces its own error toast when the save fails', async () => {
+ updatePostConfig.mockRejectedValue(new Error('nope'));
+ await renderPlan();
+ fireEvent.click(screen.getByRole('button', { name: /Save/ }));
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalled());
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/meatspace/post/constants.js b/client/src/components/meatspace/post/constants.js
index ea4dfb8886..89a8314377 100644
--- a/client/src/components/meatspace/post/constants.js
+++ b/client/src/components/meatspace/post/constants.js
@@ -33,58 +33,126 @@ export function countLlmCorrect(scoredResponses = []) {
return scoredResponses.filter(r => (r?.llmScore ?? r?.score ?? 0) >= LLM_TRAINING_CORRECT_THRESHOLD).length;
}
-// Domain definitions for 5-minute balanced sessions
-export const DOMAINS = {
- math: {
+// ---------------------------------------------------------------------------
+// Practice topics (issue #3252)
+// ---------------------------------------------------------------------------
+// MIRROR of server/lib/postTopics.js `POST_TOPICS` — the single source of truth
+// for "what am I actually studying?". Keep the two identical: id / label /
+// module / surface / drillTypes are asserted field-for-field by
+// server/lib/postTopics.mirror.test.js, which imports THIS file.
+//
+// Only the plain registry data lives here; the UI-only presentation (icon,
+// color, per-domain time budget) is layered on in TOPIC_UI below, so a topic
+// added server-side shows up here as soon as its UI row is filled in.
+export const POST_TOPICS = [
+ {
+ id: 'math',
label: 'Mental Math',
- icon: 'Calculator',
- color: 'text-blue-400',
- bgColor: 'bg-blue-500/20',
- timeBudgetSec: 60,
+ module: 'mental-math',
+ surface: 'session',
drillTypes: ['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation'],
},
- memory: {
+ {
+ id: 'memory',
label: 'Memory',
- icon: 'BookOpen',
- color: 'text-green-400',
- bgColor: 'bg-green-500/20',
- timeBudgetSec: 90,
- drillTypes: ['memory-sequence', 'memory-element-flash'],
+ module: 'memory',
+ surface: 'standalone',
+ drillTypes: ['memory-fill-blank', 'memory-sequence', 'memory-element-flash'],
},
- wordplay: {
+ {
+ id: 'wordplay',
label: 'Wordplay',
- icon: 'MessageCircle',
- color: 'text-purple-400',
- bgColor: 'bg-purple-500/20',
- timeBudgetSec: 60,
+ module: 'llm-drills',
+ surface: 'session',
drillTypes: ['pun-wordplay', 'word-association', 'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist'],
},
- verbal: {
+ {
+ id: 'verbal',
label: 'Verbal Agility',
- icon: 'Mic',
- color: 'text-amber-400',
- bgColor: 'bg-amber-500/20',
- timeBudgetSec: 60,
+ module: 'llm-drills',
+ surface: 'session',
drillTypes: ['story-recall', 'verbal-fluency', 'wit-comeback'],
},
- imagination: {
+ {
+ id: 'imagination',
label: 'Imagination',
- icon: 'Sparkles',
- color: 'text-cyan-400',
- bgColor: 'bg-cyan-500/20',
- timeBudgetSec: 60,
+ module: 'llm-drills',
+ surface: 'session',
drillTypes: ['what-if', 'alternative-uses', 'story-prompt', 'invention-pitch', 'reframe'],
},
- cognitive: {
+ {
+ id: 'cognitive',
label: 'Cognitive',
- icon: 'Brain',
- color: 'text-rose-400',
- bgColor: 'bg-rose-500/20',
- timeBudgetSec: 90,
+ module: 'cognitive',
+ surface: 'session',
drillTypes: ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time'],
},
+ {
+ id: 'morse',
+ label: 'Morse',
+ module: null,
+ surface: 'standalone',
+ drillTypes: ['morse-copy', 'morse-head-copy', 'morse-send'],
+ },
+];
+
+export const TOPIC_IDS = POST_TOPICS.map(t => t.id);
+
+// Per-topic presentation. `timeBudgetSec` is only meaningful for topics that
+// compose into a session (it sizes the drill's slice of a 5-minute Quick run);
+// Morse carries none because it never composes.
+export const TOPIC_UI = {
+ math: { icon: 'Calculator', color: 'text-blue-400', bgColor: 'bg-blue-500/20', timeBudgetSec: 60 },
+ memory: { icon: 'BookOpen', color: 'text-green-400', bgColor: 'bg-green-500/20', timeBudgetSec: 90 },
+ wordplay: { icon: 'MessageCircle', color: 'text-purple-400', bgColor: 'bg-purple-500/20', timeBudgetSec: 60 },
+ verbal: { icon: 'Mic', color: 'text-amber-400', bgColor: 'bg-amber-500/20', timeBudgetSec: 60 },
+ imagination: { icon: 'Sparkles', color: 'text-cyan-400', bgColor: 'bg-cyan-500/20', timeBudgetSec: 60 },
+ cognitive: { icon: 'Brain', color: 'text-rose-400', bgColor: 'bg-rose-500/20', timeBudgetSec: 90 },
+ morse: { icon: 'Radio', color: 'text-sky-400', bgColor: 'bg-sky-500/20' },
};
+/** The topic that owns a drill type, or `null` for an unmapped/legacy type. */
+export function resolveTopicForDrillType(type) {
+ return POST_TOPICS.find(t => t.drillTypes.includes(type)) || null;
+}
+
+/**
+ * Whether a topic participates in composition/recommendations under `config`.
+ * MIRRORS the server's `isTopicEnabled` — absent entry = enabled, so a config
+ * that predates the `topics` key behaves exactly as it did before.
+ */
+export function isTopicEnabled(config, topicId) {
+ if (!topicId) return true;
+ return config?.topics?.[topicId]?.enabled !== false;
+}
+
+/**
+ * MIRRORS the server's `isMemoryItemEnabled` — a per-item opt-out that keeps the
+ * item's mastery/schedule history and its own practice page, and only removes it
+ * from the automatic rotation.
+ */
+export function isMemoryItemEnabled(config, itemId) {
+ if (!itemId) return true;
+ if (!isTopicEnabled(config, 'memory')) return false;
+ return config?.memory?.items?.[itemId]?.enabled !== false;
+}
+
+// Domain definitions for 5-minute balanced sessions — DERIVED from POST_TOPICS
+// so the domain list has exactly one owner. A POST *domain* is a topic that
+// reports a coarse module (i.e. can produce a scored POST task); Morse has a
+// null module and is therefore not a domain. Drill types the session picker
+// can't run yet (POST_UNSUPPORTED_DRILL_TYPES) are filtered out here, so
+// DOMAINS keeps exactly the drill lists the launcher has always composed from.
+export const DOMAINS = Object.fromEntries(
+ POST_TOPICS
+ .filter(t => t.module)
+ .map(t => [t.id, {
+ label: t.label,
+ ...TOPIC_UI[t.id],
+ drillTypes: t.drillTypes.filter(dt => !POST_UNSUPPORTED_DRILL_TYPES.includes(dt)),
+ }])
+);
+
// Map drill type → domain key
export const DRILL_TO_DOMAIN = {};
for (const [domainKey, domain] of Object.entries(DOMAINS)) {
@@ -93,6 +161,55 @@ for (const [domainKey, domain] of Object.entries(DOMAINS)) {
}
}
+// Coarse module → the config block that carries its per-drill `enabled` flags.
+// Mirrors the server's MODULE_CONFIG_KEY (meatspacePost.js), extended with
+// `memory` now that it has a real config block (issue #3252).
+export const MODULE_CONFIG_KEY = {
+ 'mental-math': 'mentalMath',
+ 'llm-drills': 'llmDrills',
+ cognitive: 'cognitive',
+ memory: 'memory',
+};
+
+/** Whether a coarse module passes the `sessionModules` composition filter. */
+export function isModuleInSession(config, module) {
+ const sm = Array.isArray(config?.sessionModules) ? config.sessionModules : null;
+ // null = legacy/absent → all modules allowed; an explicit array (INCLUDING an
+ // empty one) is honored as-is.
+ return sm === null || sm.includes(module);
+}
+
+/**
+ * The drill types a Full/Quick composed session would actually run right now,
+ * grouped by topic id — the data behind the Practice Plan's "your daily POST
+ * will include…" summary (issue #3252).
+ *
+ * MIRRORS PostSessionLauncher's filter chain, in the same order: topic enabled →
+ * `sessionModules` → module `enabled` → per-drill `enabled`. It iterates the
+ * SAVED config's `drillTypes` entries (not the registry's full list) for the
+ * same reason the launcher does: a drill type absent from the config was never
+ * offered by the launcher either, so the preview must not invent it. Math drills
+ * are opt-IN (`enabled` truthy) while LLM/cognitive/memory are opt-OUT
+ * (`enabled !== false`) — again matching the launcher exactly.
+ */
+export function composedSessionDrillTypes(config) {
+ const out = {};
+ for (const topic of POST_TOPICS) {
+ if (topic.surface !== 'session' || !topic.module) continue;
+ if (!isTopicEnabled(config, topic.id)) continue;
+ if (!isModuleInSession(config, topic.module)) continue;
+ const mod = config?.[MODULE_CONFIG_KEY[topic.module]];
+ if (!mod || mod.enabled === false) continue;
+ const types = topic.drillTypes.filter((t) => {
+ const cfg = mod.drillTypes?.[t];
+ if (!cfg) return false;
+ return topic.module === 'mental-math' ? !!cfg.enabled : cfg.enabled !== false;
+ });
+ if (types.length) out[topic.id] = types;
+ }
+ return out;
+}
+
// Human-readable labels for all drill types
export const DRILL_LABELS = {
'doubling-chain': 'Doubling Chain',
diff --git a/client/src/components/meatspace/post/constants.test.js b/client/src/components/meatspace/post/constants.test.js
index 1a35ed858e..865d85fe98 100644
--- a/client/src/components/meatspace/post/constants.test.js
+++ b/client/src/components/meatspace/post/constants.test.js
@@ -1,5 +1,9 @@
import { describe, it, expect } from 'vitest';
-import { computeDomainAverages, domainLabel, computeGoalProgress, hasGoals } from './constants';
+import {
+ computeDomainAverages, domainLabel, computeGoalProgress, hasGoals,
+ POST_TOPICS, DOMAINS, DRILL_TO_DOMAIN, composedSessionDrillTypes,
+ isTopicEnabled, isMemoryItemEnabled, resolveTopicForDrillType,
+} from './constants';
describe('domainLabel', () => {
it('maps known domain keys to their human label', () => {
@@ -106,3 +110,108 @@ describe('computeGoalProgress (issue #2100)', () => {
expect(computeGoalProgress(undefined, {})).toEqual([]);
});
});
+
+// Practice-topic registry (issue #3252). DOMAINS is now DERIVED from POST_TOPICS
+// rather than hand-maintained, so these lock in that the derivation reproduces
+// exactly what the launcher has always composed from.
+describe('POST_TOPICS → DOMAINS derivation (issue #3252)', () => {
+ it('derives exactly the six scored domains, in order — Morse is not a domain', () => {
+ expect(Object.keys(DOMAINS)).toEqual(['math', 'memory', 'wordplay', 'verbal', 'imagination', 'cognitive']);
+ expect(DOMAINS.morse).toBeUndefined();
+ });
+
+ it('keeps each domain\'s presentation fields', () => {
+ for (const [key, domain] of Object.entries(DOMAINS)) {
+ expect(domain.label, key).toBeTruthy();
+ expect(domain.icon, key).toBeTruthy();
+ expect(domain.color, key).toMatch(/^text-/);
+ expect(domain.timeBudgetSec, key).toBeGreaterThan(0);
+ }
+ });
+
+ it('excludes drill types the session picker cannot run', () => {
+ // memory-fill-blank belongs to the memory TOPIC (it has a config block) but
+ // is not offered by the session picker — DOMAINS must not gain it.
+ expect(POST_TOPICS.find(t => t.id === 'memory').drillTypes).toContain('memory-fill-blank');
+ expect(DOMAINS.memory.drillTypes).toEqual(['memory-sequence', 'memory-element-flash']);
+ expect(DRILL_TO_DOMAIN['memory-fill-blank']).toBeUndefined();
+ });
+
+ it('maps every domain drill type back to its domain', () => {
+ for (const [key, domain] of Object.entries(DOMAINS)) {
+ for (const type of domain.drillTypes) expect(DRILL_TO_DOMAIN[type]).toBe(key);
+ }
+ });
+});
+
+describe('composedSessionDrillTypes (issue #3252)', () => {
+ const config = {
+ mentalMath: { enabled: true, drillTypes: { multiplication: { enabled: true }, powers: { enabled: false } } },
+ llmDrills: { enabled: true, drillTypes: { 'pun-wordplay': { enabled: true }, 'wit-comeback': {} } },
+ cognitive: { enabled: true, drillTypes: { 'n-back': { enabled: true } } },
+ };
+
+ it('groups the drills a composed session would run, by topic', () => {
+ expect(composedSessionDrillTypes(config)).toEqual({
+ math: ['multiplication'],
+ // `wit-comeback` has no `enabled` field — LLM drills are opt-OUT, so it runs.
+ wordplay: ['pun-wordplay'],
+ verbal: ['wit-comeback'],
+ cognitive: ['n-back'],
+ });
+ });
+
+ it('math drills are opt-IN: an entry with no `enabled` field does not run', () => {
+ const out = composedSessionDrillTypes({ mentalMath: { drillTypes: { multiplication: {} } } });
+ expect(out.math).toBeUndefined();
+ });
+
+ it('drops a topic the user switched off, keeping its module siblings', () => {
+ const out = composedSessionDrillTypes({ ...config, topics: { verbal: { enabled: false } } });
+ expect(out.wordplay).toEqual(['pun-wordplay']);
+ expect(out.verbal).toBeUndefined();
+ });
+
+ it('still honors the coarse sessionModules filter', () => {
+ const out = composedSessionDrillTypes({ ...config, sessionModules: ['mental-math'] });
+ expect(Object.keys(out)).toEqual(['math']);
+ });
+
+ it('never includes a standalone topic (memory / morse)', () => {
+ const out = composedSessionDrillTypes({
+ ...config,
+ memory: { enabled: true, drillTypes: { 'memory-sequence': { enabled: true } } },
+ morse: { enabled: true },
+ });
+ expect(out.memory).toBeUndefined();
+ expect(out.morse).toBeUndefined();
+ });
+});
+
+describe('isTopicEnabled / isMemoryItemEnabled client mirrors', () => {
+ it('absent = enabled, so a legacy config runs everything', () => {
+ expect(isTopicEnabled({}, 'wordplay')).toBe(true);
+ expect(isMemoryItemEnabled({}, 'elements-song')).toBe(true);
+ });
+
+ it('only an explicit false disables', () => {
+ expect(isTopicEnabled({ topics: { wordplay: { enabled: false } } }, 'wordplay')).toBe(false);
+ expect(isMemoryItemEnabled({ memory: { items: { 'elements-song': { enabled: false } } } }, 'elements-song')).toBe(false);
+ });
+
+ it('a disabled memory topic disables every item under it', () => {
+ expect(isMemoryItemEnabled({ topics: { memory: { enabled: false } } }, 'raven')).toBe(false);
+ });
+});
+
+describe('resolveTopicForDrillType client mirror', () => {
+ it('splits the llm-drills module into its three topics', () => {
+ expect(resolveTopicForDrillType('bridge-word').id).toBe('wordplay');
+ expect(resolveTopicForDrillType('story-recall').id).toBe('verbal');
+ expect(resolveTopicForDrillType('reframe').id).toBe('imagination');
+ });
+
+ it('returns null for an unmapped type', () => {
+ expect(resolveTopicForDrillType('nope')).toBeNull();
+ });
+});
diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsx
index b42e011b7a..f18c1fd03a 100644
--- a/client/src/components/meatspace/tabs/PostTab.jsx
+++ b/client/src/components/meatspace/tabs/PostTab.jsx
@@ -12,6 +12,7 @@ import PostSessionDetail from '../post/PostSessionDetail';
import PostHistory from '../post/PostHistory';
import PostProgress from '../post/PostProgress';
import PostDrillConfig from '../post/PostDrillConfig';
+import PracticePlan from '../post/PracticePlan';
import MemoryBuilder from '../post/MemoryBuilder';
import MemoryPractice, { MEMORY_PRACTICE_MODE_IDS } from '../post/MemoryPractice';
import ElementsSong, { ELEMENTS_MODE_IDS } from '../post/ElementsSong';
@@ -207,6 +208,20 @@ export default function PostTab({ tab = 'launcher', subtab, mode }) {
) : (
<div className="text-gray-500">Loading configuration...</div>
);
+ case 'plan':
+ // Practice Plan owns "what am I studying" (issue #3252). Same null guard
+ // as `config`: the editor seeds its draft state once from the loaded
+ // config, so mounting before it resolves would save defaults over the
+ // user's settings.
+ return config ? (
+ <PracticePlan
+ config={config}
+ onSaved={handleConfigSaved}
+ onBack={() => navigate('/post/launcher')}
+ />
+ ) : (
+ <div className="text-gray-500">Loading practice plan...</div>
+ );
case 'wordplay':
// Selected game mode is the `:mode` sub-route (URL is source of truth),
// mirroring the Morse trainer's `:mode` routing.
diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.js
index 32e57ff3b6..b44730c3df 100644
--- a/client/src/services/apiMeatspace.js
+++ b/client/src/services/apiMeatspace.js
@@ -174,9 +174,12 @@ export const removeEyeExam = (index) => request(`/meatspace/eyes/${index}`, {
// MeatSpace - POST (Power On Self Test)
export const getPostConfig = () => request('/meatspace/post/config');
-export const updatePostConfig = (data) => request('/meatspace/post/config', {
+// `options` lets a caller that owns its own error UI pass `{ silent: true }` so
+// the failure only toasts once (see CLAUDE.md's silent-vs-toasting convention).
+export const updatePostConfig = (data, options = {}) => request('/meatspace/post/config', {
method: 'PUT',
- body: JSON.stringify(data)
+ body: JSON.stringify(data),
+ ...options
});
export const getPostSessions = (from, to) => {
const params = new URLSearchParams();
@@ -229,7 +232,7 @@ export const fillPostDrillCache = (types, providerId, model) => request('/meatsp
});
// MeatSpace - POST Memory Builder
-export const getMemoryItems = () => request('/meatspace/post/memory-items');
+export const getMemoryItems = (options = {}) => request('/meatspace/post/memory-items', options);
export const getMemoryItem = (id) => request(`/meatspace/post/memory-items/${id}`);
export const createMemoryItem = (data) => request('/meatspace/post/memory-items', {
method: 'POST',
diff --git a/server/lib/README.md b/server/lib/README.md
index 16aa88c376..20d559c381 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -251,6 +251,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `postAdaptive.js` | Pure POST adaptive-difficulty policy — nudges a math drill's primary knob (`steps`/`maxDigits`/`maxExponent`/`tolerancePct`) up/down within clamped bounds from recent scored performance. Opt-in via the config Adaptive toggle. |
| `postMultiplicationLadder.js` | Pure progressive multiplication ladder — mastery-gated difficulty rungs (`[1,1]` → `[1,2]` → `[1,1,1]` → …). Resolves the user's current level from per-level speed+accuracy stats so the plain multiplication drill ramps up instead of starting at a fixed hard difficulty. On by default. Built on `postProgression.js`. |
| `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. |
+| `postTopics.js` | Pure POST practice-topic registry — `POST_TOPICS` (`{ id, label, module, surface, drillTypes }`) is the single source of truth for "what am I studying?", plus `resolveTopicForDrillType` / `isTopicEnabled` / `isMemoryItemEnabled`. Gates session composition and recommendations, incl. the standalone Memory and Morse surfaces. Mirrored to the client's post `constants.js` (parity test). |
| `postStreak.js` | Pure DST-safe POST practice-streak math — the single `computePostStreaks` implementation shared by scored sessions and the training log, plus `computeUnifiedStreak` (a day is active with EITHER a session or a practice entry). |
| `planIds.js` | Utilities for PLAN.md `[slug]` IDs. |
| `renderSlot.js` | Render-slot helpers for `(proof\|final)Image` per stage. |
diff --git a/server/lib/index.js b/server/lib/index.js
index d589073141..bd6dd66400 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -227,6 +227,7 @@ export * from './postAdaptive.js';
export * from './postMultiplicationLadder.js';
export * from './postProgression.js';
export * from './postStreak.js';
+export * from './postTopics.js';
export * from './planIds.js';
export * from './renderSlot.js';
export * from './renderTargets.js';
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 32b7230d04..cccdec62b3 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -186,6 +186,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.post.memory.elements.lyrics', path: '/post/memory/elements/fill-blank', label: 'Elements Fill the Lyrics', section: 'POST', aliases: ['elements-fill-blank', 'fill-the-lyrics', 'elements lyrics'], keywords: ['lyrics', 'fill in the blank', 'recall', 'tom lehrer', 'song'] },
{ id: 'nav.post.memory.elements.learn', path: '/post/memory/elements/learn', label: 'Elements Learn Lyrics', section: 'POST', aliases: ['elements-learn', 'learn-lyrics', 'elements learn'], keywords: ['read', 'verses', 'study', 'lyrics', 'tom lehrer', 'song'] },
{ id: 'nav.post.morse', path: '/post/morse', label: 'Morse', section: 'POST', aliases: ['post-morse', 'morse', 'morse-code'], keywords: ['cw', 'ham', 'radio', 'koch', 'cognitive'] },
+ { id: 'nav.post.plan', path: '/post/plan', label: 'Practice Plan', section: 'POST', aliases: ['post-plan', 'practice-plan', 'practice plan', 'plan'], keywords: ['topics', 'enable', 'disable', 'opt out', 'what am i studying', 'study plan', 'subjects'] },
{ id: 'nav.post.morse.copy', path: '/post/morse/copy', label: 'Morse Copy', section: 'POST', aliases: ['morse-copy', 'morse copy', 'copy-morse', 'morse-listen'], keywords: ['cw', 'koch', 'listen', 'decode', 'receive', 'ear'] },
{ id: 'nav.post.morse.head-copy', path: '/post/morse/head-copy', label: 'Morse Head Copy', section: 'POST', aliases: ['morse-head-copy', 'morse head copy', 'head-copy', 'head copy'], keywords: ['cw', 'koch', 'audio only', 'no reference', 'memory', 'recall'] },
{ id: 'nav.post.morse.send', path: '/post/morse/send', label: 'Morse Send', section: 'POST', aliases: ['morse-send', 'morse send', 'send-morse', 'morse-key', 'keying'], keywords: ['cw', 'key', 'straight key', 'transmit', 'dit', 'dah', 'spacebar'] },
diff --git a/server/lib/postTopics.js b/server/lib/postTopics.js
new file mode 100644
index 0000000000..f7e291e8f1
--- /dev/null
+++ b/server/lib/postTopics.js
@@ -0,0 +1,143 @@
+/**
+ * POST practice-topic registry (issue #3252).
+ *
+ * The single, enumerable answer to "what am I actually studying?" — one entry
+ * per practice area, each owning the drill types that belong to it. Every
+ * composition/recommendation path gates on this registry, so adding the next
+ * study area is a registry entry plus a toggle rather than a new bespoke gate.
+ *
+ * Shape: `{ id, label, module, surface, drillTypes[] }`
+ * - `id` — stable topic key; what the user's `config.topics` map is keyed by.
+ * - `module` — the coarse POST module this topic's scored tasks report as
+ * (`mental-math` / `llm-drills` / `cognitive` / `memory`), or
+ * `null` for a topic that never posts a scored POST task (Morse,
+ * which logs through the separate training-entry path). Topics
+ * with a non-null module are exactly the POST *domains* the
+ * client's `DOMAINS` map renders.
+ * - `surface` — `'session'` when the launcher can compose the topic's drills
+ * into a Full/Quick session, `'standalone'` when it is practiced
+ * from its own tab (Memory items, Elements, Morse).
+ * - `drillTypes`— every drill type owned by the topic, including ones not yet
+ * offered by the session picker (see the client's
+ * `POST_UNSUPPORTED_DRILL_TYPES`).
+ *
+ * Mirrored to the client in `client/src/components/meatspace/post/constants.js`
+ * (`POST_TOPICS`), where the UI-only fields — icon, color, time budget — are
+ * layered on. `server/lib/postTopics.mirror.test.js` asserts the two lists match,
+ * the same mirroring convention `canonPrompt.js` and `MEMORY_DRILL_TYPES` use.
+ *
+ * Enablement convention — **absent = enabled**, matching the existing per-drill
+ * `drillTypes` convention: only an explicit `false` disables. That is what keeps
+ * this change additive with no migration — a config saved before `topics`
+ * existed behaves exactly as it did.
+ */
+
+export const POST_TOPICS = [
+ {
+ id: 'math',
+ label: 'Mental Math',
+ module: 'mental-math',
+ surface: 'session',
+ drillTypes: ['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation'],
+ },
+ {
+ id: 'memory',
+ label: 'Memory',
+ module: 'memory',
+ surface: 'standalone',
+ drillTypes: ['memory-fill-blank', 'memory-sequence', 'memory-element-flash'],
+ },
+ {
+ id: 'wordplay',
+ label: 'Wordplay',
+ module: 'llm-drills',
+ surface: 'session',
+ drillTypes: ['pun-wordplay', 'word-association', 'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist'],
+ },
+ {
+ id: 'verbal',
+ label: 'Verbal Agility',
+ module: 'llm-drills',
+ surface: 'session',
+ drillTypes: ['story-recall', 'verbal-fluency', 'wit-comeback'],
+ },
+ {
+ id: 'imagination',
+ label: 'Imagination',
+ module: 'llm-drills',
+ surface: 'session',
+ drillTypes: ['what-if', 'alternative-uses', 'story-prompt', 'invention-pitch', 'reframe'],
+ },
+ {
+ id: 'cognitive',
+ label: 'Cognitive',
+ module: 'cognitive',
+ surface: 'session',
+ drillTypes: ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time'],
+ },
+ {
+ // Morse is deliberately outside POST_MODULES (it posts through the separate,
+ // unrestricted training-entry path, never a scored POST task) — hence a null
+ // module. It still needs a topic so a user who isn't learning CW can switch
+ // off its "Up next" recommendations (issue #3252).
+ id: 'morse',
+ label: 'Morse',
+ module: null,
+ surface: 'standalone',
+ drillTypes: ['morse-copy', 'morse-head-copy', 'morse-send'],
+ },
+];
+
+export const TOPIC_IDS = POST_TOPICS.map(t => t.id);
+
+/** Topics the launcher can compose into a Full/Quick session. */
+export const SESSION_TOPIC_IDS = POST_TOPICS.filter(t => t.surface === 'session').map(t => t.id);
+
+// drill type → topic, built once at module load.
+const TOPIC_BY_DRILL_TYPE = {};
+for (const topic of POST_TOPICS) {
+ for (const type of topic.drillTypes) TOPIC_BY_DRILL_TYPE[type] = topic;
+}
+
+/**
+ * The topic that owns a drill type, or `null` for an unmapped/legacy type.
+ * Callers treat `null` as "not topic-gated" rather than "disabled", so a drill
+ * type added ahead of its registry entry is never silently suppressed.
+ */
+export function resolveTopicForDrillType(type) {
+ return TOPIC_BY_DRILL_TYPE[type] || null;
+}
+
+/** The topic entry for an id, or `null`. */
+export function getTopic(topicId) {
+ return POST_TOPICS.find(t => t.id === topicId) || null;
+}
+
+/**
+ * Whether a topic participates in composition/recommendations under `config`.
+ * Absent entry = enabled (see the module header) — only an explicit `false`
+ * disables, so a legacy config with no `topics` key enables everything.
+ * An unknown topic id is treated as enabled for the same forward-compat reason.
+ */
+export function isTopicEnabled(config, topicId) {
+ if (!topicId) return true;
+ return config?.topics?.[topicId]?.enabled !== false;
+}
+
+/** Ids of every currently-enabled topic, in registry order. */
+export function enabledTopicIds(config) {
+ return TOPIC_IDS.filter(id => isTopicEnabled(config, id));
+}
+
+/**
+ * Whether an individual memory item participates in recommendations and in
+ * `generateMemoryDrill`'s lowest-mastery candidate pool. Same absent = enabled
+ * convention. A disabled item keeps its full mastery/schedule history and stays
+ * practiceable on demand from its own page — this only scopes the *automatic*
+ * paths (issue #3252). A null/absent id is never filtered.
+ */
+export function isMemoryItemEnabled(config, itemId) {
+ if (!itemId) return true;
+ if (!isTopicEnabled(config, 'memory')) return false;
+ return config?.memory?.items?.[itemId]?.enabled !== false;
+}
diff --git a/server/lib/postTopics.mirror.test.js b/server/lib/postTopics.mirror.test.js
new file mode 100644
index 0000000000..368c8b0c74
--- /dev/null
+++ b/server/lib/postTopics.mirror.test.js
@@ -0,0 +1,63 @@
+/**
+ * Mirror parity test for server/lib/postTopics.js ↔ the client's POST topic
+ * mirror in client/src/components/meatspace/post/constants.js (issue #3252).
+ *
+ * The registry is server-owned; the client mirrors the plain data so the
+ * launcher, Practice Plan, and config UI can gate without a round-trip. If the
+ * two drift, a topic the server filters on would be invisible to the UI (or
+ * vice versa) — hence a hard parity assert rather than a convention.
+ *
+ * Mirrored: the POST_TOPICS literal and the two enablement predicates that the
+ * client re-implements verbatim. NOT mirrored: `resolveTopicForDrillType`, which
+ * the server backs with a prebuilt lookup map (built once at module load) while
+ * the client does a linear find over a 7-entry list — same contract, different
+ * implementation, so it's asserted behaviorally in postTopics.test.js instead.
+ *
+ * Comparison strips comments and normalizes whitespace (see lib/mirrorParity.js),
+ * so JSDoc divergence is allowed and only code differences fail.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { resolve, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { compareDeclaration } from './mirrorParity.js';
+import { POST_TOPICS } from './postTopics.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+const SERVER_PATH = resolve(__dirname, 'postTopics.js');
+const CLIENT_PATH = resolve(__dirname, '../../client/src/components/meatspace/post/constants.js');
+
+const MIRRORED_NAMES = ['POST_TOPICS', 'isTopicEnabled', 'isMemoryItemEnabled'];
+
+describe('postTopics server↔client mirror parity', () => {
+ const serverSrc = readFileSync(SERVER_PATH, 'utf8');
+ const clientSrc = readFileSync(CLIENT_PATH, 'utf8');
+
+ it('both files are non-empty', () => {
+ expect(serverSrc.length).toBeGreaterThan(100);
+ expect(clientSrc.length).toBeGreaterThan(100);
+ });
+
+ for (const name of MIRRORED_NAMES) {
+ it(`${name} is present and identical on both sides (code only)`, () => {
+ const { serverDecl, clientDecl, serverNorm, clientNorm } =
+ compareDeclaration(serverSrc, clientSrc, name);
+
+ expect(serverDecl, `server/lib/postTopics.js is missing declaration: ${name}`).not.toBeNull();
+ expect(clientDecl, `client post constants.js is missing declaration: ${name}`).not.toBeNull();
+ expect(clientNorm, `"${name}" code diverged between server and client`).toBe(serverNorm);
+ });
+ }
+
+ it('the client declares presentation for every topic', () => {
+ // TOPIC_UI is client-only (icons/colors have no server meaning), but a
+ // topic added server-side with no UI row would render unstyled and,
+ // for a domain, lose its per-domain time budget.
+ for (const topic of POST_TOPICS) {
+ expect(clientSrc, `TOPIC_UI is missing a row for topic "${topic.id}"`)
+ .toMatch(new RegExp(`^\\s*${topic.id}:\\s*\\{\\s*icon:`, 'm'));
+ }
+ });
+});
diff --git a/server/lib/postTopics.test.js b/server/lib/postTopics.test.js
new file mode 100644
index 0000000000..aa22e9a379
--- /dev/null
+++ b/server/lib/postTopics.test.js
@@ -0,0 +1,132 @@
+import { describe, it, expect } from 'vitest';
+import {
+ POST_TOPICS,
+ TOPIC_IDS,
+ SESSION_TOPIC_IDS,
+ resolveTopicForDrillType,
+ getTopic,
+ isTopicEnabled,
+ enabledTopicIds,
+ isMemoryItemEnabled,
+} from './postTopics.js';
+import { LLM_DRILL_TYPES, MATH_DRILL_TYPES, MEMORY_DRILL_TYPES, COGNITIVE_DRILL_TYPES, MORSE_DRILL_TYPES } from './postValidation.js';
+
+describe('POST_TOPICS registry (issue #3252)', () => {
+ it('has unique ids and a well-formed entry per topic', () => {
+ expect(new Set(TOPIC_IDS).size).toBe(TOPIC_IDS.length);
+ for (const t of POST_TOPICS) {
+ expect(typeof t.id).toBe('string');
+ expect(typeof t.label).toBe('string');
+ expect(['session', 'standalone']).toContain(t.surface);
+ expect(Array.isArray(t.drillTypes)).toBe(true);
+ expect(t.drillTypes.length).toBeGreaterThan(0);
+ }
+ });
+
+ it('never maps one drill type to two topics', () => {
+ const all = POST_TOPICS.flatMap(t => t.drillTypes);
+ expect(new Set(all).size).toBe(all.length);
+ });
+
+ it('covers the standalone surfaces that previously had no opt-out', () => {
+ expect(getTopic('memory').surface).toBe('standalone');
+ expect(getTopic('morse').surface).toBe('standalone');
+ // Morse never posts a scored POST task, so it carries no coarse module.
+ expect(getTopic('morse').module).toBeNull();
+ });
+
+ it('SESSION_TOPIC_IDS is exactly the composable subset', () => {
+ expect(SESSION_TOPIC_IDS).toEqual(['math', 'wordplay', 'verbal', 'imagination', 'cognitive']);
+ });
+
+ // The registry partitions the SAME drill types the config schema validates. If
+ // it drifts, a drill type would either be ungated (no topic owns it) or the
+ // Practice Plan would render a toggle the schema then rejects on save.
+ it("each module's topics partition exactly that module's schema drill types", () => {
+ const typesForModule = (module) => POST_TOPICS
+ .filter(t => t.module === module)
+ .flatMap(t => t.drillTypes)
+ .sort();
+ expect(typesForModule('llm-drills')).toEqual([...LLM_DRILL_TYPES].sort());
+ expect(typesForModule('cognitive')).toEqual([...COGNITIVE_DRILL_TYPES].sort());
+ expect(typesForModule('memory')).toEqual([...MEMORY_DRILL_TYPES].sort());
+ expect(typesForModule('mental-math')).toEqual([...MATH_DRILL_TYPES].sort());
+ // Morse carries a null module and its own drill-type list.
+ expect(getTopic('morse').drillTypes).toEqual(MORSE_DRILL_TYPES);
+ });
+});
+
+describe('resolveTopicForDrillType', () => {
+ it('resolves each of the four llm-drills topics distinctly', () => {
+ expect(resolveTopicForDrillType('bridge-word').id).toBe('wordplay');
+ expect(resolveTopicForDrillType('wit-comeback').id).toBe('verbal');
+ expect(resolveTopicForDrillType('what-if').id).toBe('imagination');
+ });
+
+ it('resolves standalone drill types', () => {
+ expect(resolveTopicForDrillType('memory-element-flash').id).toBe('memory');
+ expect(resolveTopicForDrillType('morse-copy').id).toBe('morse');
+ });
+
+ it('returns null for an unmapped type so callers can treat it as un-gated', () => {
+ expect(resolveTopicForDrillType('some-future-drill')).toBeNull();
+ expect(resolveTopicForDrillType(undefined)).toBeNull();
+ });
+});
+
+describe('isTopicEnabled — absent = enabled (no migration)', () => {
+ it('treats a legacy config with no topics key as everything enabled', () => {
+ for (const id of TOPIC_IDS) expect(isTopicEnabled({}, id)).toBe(true);
+ expect(isTopicEnabled(null, 'wordplay')).toBe(true);
+ expect(isTopicEnabled(undefined, 'morse')).toBe(true);
+ });
+
+ it('only an explicit false disables', () => {
+ expect(isTopicEnabled({ topics: { wordplay: {} } }, 'wordplay')).toBe(true);
+ expect(isTopicEnabled({ topics: { wordplay: { enabled: true } } }, 'wordplay')).toBe(true);
+ expect(isTopicEnabled({ topics: { wordplay: { enabled: false } } }, 'wordplay')).toBe(false);
+ });
+
+ it('leaves sibling topics untouched', () => {
+ const config = { topics: { verbal: { enabled: false } } };
+ expect(isTopicEnabled(config, 'verbal')).toBe(false);
+ expect(isTopicEnabled(config, 'wordplay')).toBe(true);
+ });
+
+ it('treats an unknown topic id as enabled (forward-compat)', () => {
+ expect(isTopicEnabled({ topics: {} }, 'not-a-topic')).toBe(true);
+ });
+});
+
+describe('enabledTopicIds', () => {
+ it('returns every topic for a legacy config', () => {
+ expect(enabledTopicIds({})).toEqual(TOPIC_IDS);
+ });
+
+ it('drops only the explicitly disabled ones, in registry order', () => {
+ const config = { topics: { morse: { enabled: false }, verbal: { enabled: false } } };
+ expect(enabledTopicIds(config)).toEqual(['math', 'memory', 'wordplay', 'imagination', 'cognitive']);
+ });
+});
+
+describe('isMemoryItemEnabled', () => {
+ it('enables every item under a legacy config', () => {
+ expect(isMemoryItemEnabled({}, 'elements-song')).toBe(true);
+ expect(isMemoryItemEnabled({ memory: {} }, 'raven')).toBe(true);
+ });
+
+ it('honors a per-item opt-out without touching siblings', () => {
+ const config = { memory: { items: { 'elements-song': { enabled: false } } } };
+ expect(isMemoryItemEnabled(config, 'elements-song')).toBe(false);
+ expect(isMemoryItemEnabled(config, 'raven')).toBe(true);
+ });
+
+ it('a disabled memory TOPIC disables every item under it', () => {
+ const config = { topics: { memory: { enabled: false } } };
+ expect(isMemoryItemEnabled(config, 'raven')).toBe(false);
+ });
+
+ it('never filters an absent item id', () => {
+ expect(isMemoryItemEnabled({ memory: { items: { x: { enabled: false } } } }, null)).toBe(true);
+ });
+});
diff --git a/server/lib/postValidation.js b/server/lib/postValidation.js
index d524e49636..e275b18a2c 100644
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@ -1,6 +1,7 @@
import { z } from 'zod';
import { CACHEABLE_TYPES } from '../services/meatspacePostDrillCache.js';
import { COGNITIVE_DRILL_TYPES } from '../services/meatspacePostCognitive.js';
+import { TOPIC_IDS } from './postTopics.js';
import { HHMM_STRICT_RE } from './timezone.js';
// =============================================================================
@@ -240,6 +241,34 @@ export const postConfigUpdateSchema = z.object({
enabled: z.boolean().optional(),
drillTypes: z.record(z.enum(COGNITIVE_DRILL_TYPES), drillTypeConfigSchema).optional()
}).optional(),
+ // Memory practice (issue #3252). Mirrors the other module blocks, plus an
+ // `items` map so an INDIVIDUAL memorized text — e.g. the seeded Elements Song
+ // — can be dropped from the daily rotation without deleting it (which would
+ // throw away its mastery/schedule history). Keys are memory item ids, so this
+ // is an open `z.string()` record rather than an enum.
+ // `partialRecord`, not `record`: an enum-keyed `z.record` is EXHAUSTIVE in
+ // zod 4 (every enum member required), which is why the sibling module blocks
+ // above force their UI to write a complete drillTypes map. These blocks are
+ // new, so they take the more forgiving contract — a patch may carry just the
+ // one flag it is changing.
+ memory: z.object({
+ enabled: z.boolean().optional(),
+ drillTypes: z.partialRecord(z.enum(MEMORY_DRILL_TYPES), drillTypeConfigSchema).optional(),
+ items: z.record(z.string(), z.object({ enabled: z.boolean().optional() })).optional()
+ }).optional(),
+ // Morse (issue #3252). Morse has no drill-type knobs here — its trainer owns
+ // its own Koch settings — so the block is just the participation toggle that
+ // suppresses the `morse-copy` stalled-progression recommendation.
+ morse: z.object({
+ enabled: z.boolean().optional()
+ }).optional(),
+ // Practice-topic participation (issue #3252) — the fine-grained "what am I
+ // studying?" layer that sits ON TOP of the coarse `sessionModules` filter.
+ // Absent entry = enabled (see server/lib/postTopics.js), so a config that
+ // predates this key behaves exactly as before — additive, no migration.
+ topics: z.partialRecord(z.enum(TOPIC_IDS), z.object({
+ enabled: z.boolean().optional()
+ })).optional(),
sessionModules: z.array(z.enum(POST_MODULES)).optional(),
// Optional practice goals (issue #2100) — see postGoalsSchema above.
goals: postGoalsSchema.optional(),
diff --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.js
index fad0649a24..0c34cc923e 100644
--- a/server/lib/postValidation.test.js
+++ b/server/lib/postValidation.test.js
@@ -12,6 +12,7 @@ import {
POST_MODULES,
POST_SUPPORTED_MEMORY_TYPES,
} from './postValidation.js';
+import { getTopic } from './postTopics.js';
describe('postConfigUpdateSchema llmDrills', () => {
// Regression: the config UI (PostDrillConfig.jsx) exposed only 5 of the 14
@@ -484,3 +485,74 @@ describe('postSessionSubmitSchema client-generated id (issue #2098)', () => {
expect(() => postSessionSubmitSchema.parse({ ...baseBody(), id: 'not-a-uuid' })).toThrow();
});
});
+
+// Practice Plan config blocks (issue #3252). All three are additive: a config
+// saved by the pre-#3252 UI must still validate byte-for-byte unchanged, which
+// is what makes this shippable with no migration.
+// Sourced from the topic registry so this test can't drift from the enums the
+// schema actually validates against (postTopics.test.js asserts registry ↔ enum
+// parity, so registry order IS the enum content).
+const MATH_DRILL_TYPE_IDS = getTopic('math').drillTypes;
+const LLM_DRILL_TYPE_IDS = ['wordplay', 'verbal', 'imagination'].flatMap(id => getTopic(id).drillTypes);
+const COGNITIVE_DRILL_TYPE_IDS = getTopic('cognitive').drillTypes;
+
+describe('postConfigUpdateSchema topics/memory/morse (issue #3252)', () => {
+ it('accepts a topics map and preserves it', () => {
+ const parsed = postConfigUpdateSchema.parse({
+ topics: { wordplay: { enabled: true }, verbal: { enabled: false }, morse: {} }
+ });
+ expect(parsed.topics).toEqual({ wordplay: { enabled: true }, verbal: { enabled: false }, morse: {} });
+ });
+
+ it('rejects a topic id that is not in the registry', () => {
+ expect(() => postConfigUpdateSchema.parse({ topics: { 'not-a-topic': { enabled: false } } })).toThrow();
+ });
+
+ it('accepts a memory block with drill types and per-item flags', () => {
+ const parsed = postConfigUpdateSchema.parse({
+ memory: {
+ enabled: true,
+ drillTypes: { 'memory-sequence': { enabled: false } },
+ items: { 'elements-song': { enabled: false }, raven: { enabled: true } }
+ }
+ });
+ expect(parsed.memory.items['elements-song']).toEqual({ enabled: false });
+ expect(parsed.memory.drillTypes['memory-sequence']).toEqual({ enabled: false });
+ });
+
+ it('rejects a memory drill type that is not a memory drill', () => {
+ expect(() => postConfigUpdateSchema.parse({ memory: { drillTypes: { 'n-back': { enabled: false } } } })).toThrow();
+ });
+
+ it('accepts a morse participation toggle', () => {
+ expect(postConfigUpdateSchema.parse({ morse: { enabled: false } }).morse).toEqual({ enabled: false });
+ });
+
+ it('a memory patch may carry just the flag it changes (partialRecord, not exhaustive)', () => {
+ const parsed = postConfigUpdateSchema.parse({ memory: { drillTypes: { 'memory-sequence': { enabled: false } } } });
+ expect(Object.keys(parsed.memory.drillTypes)).toEqual(['memory-sequence']);
+ });
+
+ it('a legacy config with none of the three keys still validates unchanged', () => {
+ // The pre-#3252 UI's exact save shape: enum-keyed `z.record` is exhaustive
+ // in zod 4, so the module blocks carry a complete drillTypes map.
+ const fullMap = (types, entry) => Object.fromEntries(types.map(t => [t, { ...entry }]));
+ const legacy = {
+ mentalMath: { enabled: true, drillTypes: fullMap(MATH_DRILL_TYPE_IDS, { enabled: true, timeLimitSec: 60 }) },
+ llmDrills: { enabled: true, providerId: null, model: null, drillTypes: fullMap(LLM_DRILL_TYPE_IDS, { enabled: false, count: 5 }) },
+ cognitive: { enabled: true, drillTypes: fullMap(COGNITIVE_DRILL_TYPE_IDS, { enabled: true, progressive: true }) },
+ sessionModules: ['mental-math', 'cognitive'],
+ goals: { dailyMinutes: 20 },
+ scoring: { weights: { 'mental-math': 1 } },
+ adaptive: { enabled: false },
+ reminder: { enabled: true, time: '09:30' }
+ };
+ const parsed = postConfigUpdateSchema.parse(legacy);
+ expect(parsed).toEqual(legacy);
+ // No `topics` / `memory` / `morse` invented on the way through — absent
+ // stays absent, and absent means enabled. That is the no-migration promise.
+ expect(parsed.topics).toBeUndefined();
+ expect(parsed.memory).toBeUndefined();
+ expect(parsed.morse).toBeUndefined();
+ });
+});
diff --git a/server/routes/meatspacePostRoutes.drill.test.js b/server/routes/meatspacePostRoutes.drill.test.js
index d16df3fa7d..6645266eff 100644
--- a/server/routes/meatspacePostRoutes.drill.test.js
+++ b/server/routes/meatspacePostRoutes.drill.test.js
@@ -29,12 +29,15 @@ vi.mock('../services/meatspacePost.js', () => ({
resolveDrillConfig: vi.fn(),
generateDrill: vi.fn(),
getPostReviewReps: vi.fn(),
+ // The memory branch reads the saved config to scope generateMemoryDrill's
+ // auto-picked item to the user's enabled Practice Plan topics (issue #3252).
+ getPostConfig: vi.fn(),
}));
import { getCachedDrill, triggerReplenish } from '../services/meatspacePostDrillCache.js';
import { generateLlmDrill } from '../services/meatspacePostLlm.js';
import { generateMemoryDrill } from '../services/meatspacePostMemory.js';
-import { resolveDrillConfig, generateDrill, getPostReviewReps } from '../services/meatspacePost.js';
+import { resolveDrillConfig, generateDrill, getPostReviewReps, getPostConfig } from '../services/meatspacePost.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import meatspacePostRoutes from './meatspacePostRoutes.js';
@@ -105,18 +108,26 @@ describe('POST /api/meatspace/post/drill', () => {
describe('Memory drill types', () => {
it('strips the memory- prefix into `mode` and forwards count/memoryItemId', async () => {
const drill = { type: 'memory-sequence', memoryItemId: 'song-1', questions: [] };
+ const savedConfig = { memory: { items: { 'elements-song': { enabled: false } } } };
generateMemoryDrill.mockResolvedValue(drill);
+ getPostConfig.mockResolvedValue(savedConfig);
const r = await request(app).post('/api/meatspace/post/drill')
.send({ type: 'memory-sequence', config: { count: 3, memoryItemId: 'song-1' } });
expect(r.status).toBe(200);
expect(r.body).toEqual(drill);
- expect(generateMemoryDrill).toHaveBeenCalledWith({ mode: 'sequence', count: 3, memoryItemId: 'song-1' });
+ // The saved config rides along so the generator can scope its
+ // lowest-mastery candidate pool to enabled items (issue #3252).
+ expect(generateMemoryDrill).toHaveBeenCalledWith(
+ { mode: 'sequence', count: 3, memoryItemId: 'song-1' },
+ savedConfig,
+ );
});
it('throws MEMORY_DRILL_FAILED when no drill can be generated', async () => {
generateMemoryDrill.mockResolvedValue(null);
+ getPostConfig.mockResolvedValue({});
const r = await request(app).post('/api/meatspace/post/drill')
.send({ type: 'memory-element-flash', config: {} });
diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.js
index 1ac504596d..6654d81fe9 100644
--- a/server/routes/meatspacePostRoutes.js
+++ b/server/routes/meatspacePostRoutes.js
@@ -166,7 +166,13 @@ router.post('/post/drill', asyncHandler(async (req, res) => {
if (MEMORY_DRILL_TYPES.includes(data.type)) {
const mode = data.type.replace('memory-', '');
- const drill = await memoryService.generateMemoryDrill({ mode, count: data.config?.count, memoryItemId: data.config?.memoryItemId });
+ // The saved config scopes the auto-picked (lowest-mastery) item to the ones
+ // still enabled in the user's Practice Plan (issue #3252); an explicit
+ // memoryItemId bypasses it.
+ const drill = await memoryService.generateMemoryDrill(
+ { mode, count: data.config?.count, memoryItemId: data.config?.memoryItemId },
+ await postService.getPostConfig(),
+ );
if (!drill) {
throw new ServerError('Failed to generate memory drill', { status: 500, code: 'MEMORY_DRILL_FAILED' });
}
@@ -448,7 +454,7 @@ router.get('/post/memory-items/:id/chunk-mastery', asyncHandler(async (req, res)
*/
router.post('/post/memory-drill', asyncHandler(async (req, res) => {
const data = validateRequest(memoryDrillRequestSchema, req.body);
- const drill = await memoryService.generateMemoryDrill(data);
+ const drill = await memoryService.generateMemoryDrill(data, await postService.getPostConfig());
if (!drill) throw new ServerError('No memory items available', { status: 400, code: 'NO_MEMORY_ITEMS' });
res.json(drill);
}));
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index b4d3095b01..ad4eb3a7e5 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -11,6 +11,7 @@ import { EventEmitter } from 'events';
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 { resolveTopicForDrillType, isTopicEnabled, isMemoryItemEnabled } from '../lib/postTopics.js';
import { adaptDrillConfig, ADAPTIVE_SPECS, ADAPTIVE_DEFAULTS } from '../lib/postAdaptive.js';
import { resolveMultiplicationLevel, MASTERY_DEFAULTS } from '../lib/postMultiplicationLadder.js';
import {
@@ -103,6 +104,22 @@ const DEFAULT_CONFIG = {
'reaction-time': { enabled: true, mode: 'simple', count: 15, minDelayMs: 1000, maxDelayMs: 3000, choices: 3 }
}
},
+ // Memory practice (issue #3252). Present so the block's shape is discoverable
+ // in the saved config; `items` is deliberately ABSENT — a per-item entry is
+ // only written when the user actually switches an item off, and absent =
+ // enabled, so a fresh or legacy install rotates every memory item as before.
+ memory: {
+ enabled: true,
+ drillTypes: {
+ 'memory-fill-blank': { enabled: true },
+ 'memory-sequence': { enabled: true },
+ 'memory-element-flash': { enabled: true }
+ }
+ },
+ // Morse participation (issue #3252) — on by default so existing installs keep
+ // seeing Koch-progression recommendations; a user not learning CW turns it off
+ // from the Practice Plan.
+ morse: { enabled: true },
// Default session composition is a balanced, interleaved mix of the free
// (no-provider) modules the launcher can actually compose — mental math and
// deterministic cognitive drills (issue #2100). LLM drills are deliberately
@@ -1104,12 +1121,36 @@ const MODULE_CONFIG_KEY = { 'mental-math': 'mentalMath', 'llm-drills': 'llmDrill
* Whether a recommended drill can actually be run under the current config
* (issue #2100 review): a weak-skill / stalled rec deep-links into a session,
* so recommending a drill the user has since disabled — or a module they've
- * removed from Session Composition — would be a dead end. Memory practice runs
- * from its own tab, so it's always runnable regardless of session composition.
+ * removed from Session Composition — would be a dead end.
+ *
+ * Three gates, checked in order (issue #3252):
+ * 1. The drill's practice TOPIC — off means off everywhere, including the
+ * standalone surfaces (Memory, Morse) that session composition never gated.
+ * 2. Module-specific participation — `memory` and `morse` run from their own
+ * tabs, so `sessionModules` doesn't apply to them; memory additionally
+ * honors the per-ITEM toggle when the caller knows which item is involved.
+ * 3. Session composition + the per-module/per-drill `enabled` flags.
+ *
+ * `memoryItemId` is only meaningful for `module === 'memory'`; absent means
+ * "no specific item", which is never filtered.
* Pure — exported for unit tests.
*/
-export function isRecDrillRunnable(config, module, type) {
- if (module === 'memory') return true;
+export function isRecDrillRunnable(config, module, type, memoryItemId = null) {
+ // An unmapped drill type has no topic — treat it as not topic-gated rather
+ // than disabled, so a type added ahead of its registry entry still surfaces.
+ const topic = resolveTopicForDrillType(type);
+ if (topic && !isTopicEnabled(config, topic.id)) return false;
+
+ if (module === 'memory') {
+ if (config?.memory?.enabled === false) return false;
+ const dt = config?.memory?.drillTypes?.[type];
+ if (dt && dt.enabled === false) return false;
+ return isMemoryItemEnabled(config, memoryItemId);
+ }
+ // Morse isn't a POST module (it never posts a scored task), so it is gated by
+ // its own block alone — never by sessionModules, which can't contain it.
+ if (module === 'morse') return config?.morse?.enabled !== false;
+
const sm = Array.isArray(config?.sessionModules) ? config.sessionModules : null;
// null = legacy/absent → all modules allowed; an explicit array must include it.
if (sm !== null && !sm.includes(module)) return false;
@@ -1152,19 +1193,36 @@ export async function getPostRecommendations({ limit = RECOMMENDATION_LIMIT } =
: null;
}
- // Stalled progressions — keep Morse (runs from its own tab) and any ladder
- // whose drill is still runnable under the current config.
+ // Due memory items — drop the ones the user has switched off for the daily
+ // rotation (issue #3252). The item keeps its mastery/schedule history and is
+ // still practiceable on demand from its own page; it just stops being
+ // recommended. getDueMemoryItems() itself stays unfiltered — it also backs the
+ // Memory tab's own list.
+ const enabledDueMemoryItems = dueMemoryItems
+ .filter(item => isRecDrillRunnable(config, 'memory', 'memory-sequence', item.id));
+
+ // Memory chunk re-verifications point at a specific item too, so a disabled
+ // item shouldn't surface one. Non-memory reviews pass through untouched.
+ const enabledDueReviews = dueReviews.filter(review => review.kind !== 'memory'
+ || isRecDrillRunnable(config, 'memory', review.drillType || 'memory-sequence', memoryItemIdFromReview(review)));
+
+ // Stalled progressions — Morse runs from its own tab (so it's gated by its own
+ // topic/config block rather than session composition), and any ladder whose
+ // drill is still runnable under the current config.
const stalled = stalledProgressions(mulProgress, cogProgress, {
kochLevel: morse?.kochLevel,
kochLevelSet: morse?.kochLevelSet,
maxKochLevel: MAX_KOCH_LEVEL,
- }).filter(s => s.drillType === 'morse-copy'
- || isRecDrillRunnable(config, s.drillType === 'multiplication' ? 'mental-math' : 'cognitive', s.drillType));
+ }).filter(s => isRecDrillRunnable(
+ config,
+ s.drillType === 'morse-copy' ? 'morse' : s.drillType === 'multiplication' ? 'mental-math' : 'cognitive',
+ s.drillType,
+ ));
return {
recommendations: composePostRecommendations({
- dueMemoryItems,
- dueReviews,
+ dueMemoryItems: enabledDueMemoryItems,
+ dueReviews: enabledDueReviews,
weakestSkill,
stalled,
hasHistory: sessions.length > 0,
diff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.js
index 3f071166b0..cd21a37401 100644
--- a/server/services/meatspacePostMemory.js
+++ b/server/services/meatspacePostMemory.js
@@ -9,6 +9,7 @@ import { join } from 'path';
import { randomUUID } from 'crypto';
import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
import { shuffle } from '../lib/arrayUtils.js';
+import { isMemoryItemEnabled } from '../lib/postTopics.js';
import { userLocalToday } from '../lib/timezone.js';
const MEATSPACE_DIR = PATHS.meatspace;
@@ -697,8 +698,16 @@ export async function getTrainingLog(memoryItemId, limit = 50) {
* Picks the memory item with the lowest mastery (or user-configured item)
* and creates a fill-in-the-blank or sequence recall exercise.
* Uses spaced repetition: focuses on lowest-mastery chunks.
+ *
+ * `postConfig` (the saved POST config) scopes the automatic lowest-mastery
+ * candidate pool to items the user hasn't switched off in their Practice Plan
+ * (issue #3252). An EXPLICIT `config.memoryItemId` always wins — a disabled item
+ * stays practiceable on demand from its own page, it just isn't auto-picked.
+ * When every item is disabled the pool falls back to all of them rather than
+ * failing the drill: a composed session that asked for a memory drill should
+ * still get one.
*/
-export async function generateMemoryDrill(config = {}) {
+export async function generateMemoryDrill(config = {}, postConfig = null) {
const items = await loadMemoryItems();
if (!items.length) return null;
@@ -708,7 +717,9 @@ export async function generateMemoryDrill(config = {}) {
item = items.find(i => i.id === config.memoryItemId);
}
if (!item) {
- item = items.reduce((lowest, i) => i.mastery.overallPct < lowest.mastery.overallPct ? i : lowest, items[0]);
+ const enabled = items.filter(i => isMemoryItemEnabled(postConfig, i.id));
+ const pool = enabled.length ? enabled : items;
+ item = pool.reduce((lowest, i) => i.mastery.overallPct < lowest.mastery.overallPct ? i : lowest, pool[0]);
}
const mode = config.mode || 'fill-blank';
diff --git a/server/services/meatspacePostMemory.test.js b/server/services/meatspacePostMemory.test.js
index d1d46eabf3..4a9ea01597 100644
--- a/server/services/meatspacePostMemory.test.js
+++ b/server/services/meatspacePostMemory.test.js
@@ -376,6 +376,53 @@ describe('generateMemoryDrill', () => {
const drill = await generateMemoryDrill({ mode: 'sequence', count: 1 });
expect(drill.memoryItemId).toBe('b');
});
+
+ // Practice Plan per-item participation (issue #3252). A user who doesn't want
+ // a memorized text in the daily rotation switches it off instead of deleting
+ // it — deletion would throw away its mastery/schedule history.
+ describe('enabled-item candidate pool', () => {
+ const THREE_ITEMS = {
+ items: [
+ { ...ELEMENTS_SONG, mastery: { overallPct: 5, chunks: {}, elements: {} } },
+ { id: 'a', title: 'A', type: 'text', builtin: false, mastery: { overallPct: 90, chunks: {}, elements: {} }, content: { lines: [{ text: 'Line 1' }, { text: 'Line 2' }, { text: 'Line 3' }], chunks: [] } },
+ { id: 'b', title: 'B', type: 'text', builtin: false, mastery: { overallPct: 40, chunks: {}, elements: {} }, content: { lines: [{ text: 'Line A' }, { text: 'Line B' }, { text: 'Line C' }], chunks: [] } },
+ ]
+ };
+
+ it('skips a disabled item when auto-picking the lowest-mastery target', async () => {
+ readJSONFile.mockResolvedValue(THREE_ITEMS);
+ // elements-song has the lowest mastery, so it would win — but it's off.
+ const drill = await generateMemoryDrill(
+ { mode: 'sequence', count: 1 },
+ { memory: { items: { 'elements-song': { enabled: false } } } },
+ );
+ expect(drill.memoryItemId).toBe('b');
+ });
+
+ it('still honors an EXPLICIT memoryItemId for a disabled item (its own page)', async () => {
+ readJSONFile.mockResolvedValue(THREE_ITEMS);
+ const drill = await generateMemoryDrill(
+ { mode: 'sequence', count: 1, memoryItemId: 'elements-song' },
+ { memory: { items: { 'elements-song': { enabled: false } } } },
+ );
+ expect(drill.memoryItemId).toBe('elements-song');
+ });
+
+ it('falls back to every item when the plan leaves none enabled', async () => {
+ readJSONFile.mockResolvedValue(THREE_ITEMS);
+ const drill = await generateMemoryDrill(
+ { mode: 'sequence', count: 1 },
+ { topics: { memory: { enabled: false } } },
+ );
+ expect(drill.memoryItemId).toBe('elements-song');
+ });
+
+ it('behaves exactly as before when no config is passed (legacy callers)', async () => {
+ readJSONFile.mockResolvedValue(THREE_ITEMS);
+ const drill = await generateMemoryDrill({ mode: 'sequence', count: 1 });
+ expect(drill.memoryItemId).toBe('elements-song');
+ });
+ });
});
// =============================================================================
diff --git a/server/services/meatspacePostRecommendations.test.js b/server/services/meatspacePostRecommendations.test.js
index 071a2b6fc5..0ae1721cdb 100644
--- a/server/services/meatspacePostRecommendations.test.js
+++ b/server/services/meatspacePostRecommendations.test.js
@@ -165,6 +165,46 @@ describe('isRecDrillRunnable (issue #2100)', () => {
});
});
+describe('isRecDrillRunnable topic/standalone gating (issue #3252)', () => {
+ it('a disabled TOPIC blocks its drills even when the module is allowed', () => {
+ const config = { sessionModules: ['cognitive'], topics: { cognitive: { enabled: false } } };
+ expect(isRecDrillRunnable(config, 'cognitive', 'n-back')).toBe(false);
+ });
+
+ it('topic granularity splits the three llm-drills topics apart', () => {
+ // wordplay / verbal / imagination all collapse into `llm-drills`, so only a
+ // topic-level gate can express "wordplay only".
+ const config = { sessionModules: ['llm-drills'], topics: { verbal: { enabled: false }, imagination: { enabled: false } } };
+ expect(isRecDrillRunnable(config, 'llm-drills', 'bridge-word')).toBe(true);
+ expect(isRecDrillRunnable(config, 'llm-drills', 'wit-comeback')).toBe(false);
+ expect(isRecDrillRunnable(config, 'llm-drills', 'what-if')).toBe(false);
+ });
+
+ it('morse is gated by its own block, never by sessionModules (it is not a POST module)', () => {
+ expect(isRecDrillRunnable({ sessionModules: ['mental-math'] }, 'morse', 'morse-copy')).toBe(true);
+ expect(isRecDrillRunnable({ morse: { enabled: false } }, 'morse', 'morse-copy')).toBe(false);
+ expect(isRecDrillRunnable({ topics: { morse: { enabled: false } } }, 'morse', 'morse-copy')).toBe(false);
+ });
+
+ it('memory honors the module block, the drill type, and the per-ITEM toggle', () => {
+ expect(isRecDrillRunnable({ memory: { enabled: false } }, 'memory', 'memory-sequence')).toBe(false);
+ expect(isRecDrillRunnable({ memory: { drillTypes: { 'memory-sequence': { enabled: false } } } }, 'memory', 'memory-sequence')).toBe(false);
+ const perItem = { memory: { items: { 'elements-song': { enabled: false } } } };
+ expect(isRecDrillRunnable(perItem, 'memory', 'memory-sequence', 'elements-song')).toBe(false);
+ expect(isRecDrillRunnable(perItem, 'memory', 'memory-sequence', 'raven')).toBe(true);
+ // No item id supplied → nothing to filter on.
+ expect(isRecDrillRunnable(perItem, 'memory', 'memory-sequence')).toBe(true);
+ });
+
+ it('a legacy config with no topics/memory/morse keys runs everything (no migration)', () => {
+ const legacy = { sessionModules: ['mental-math', 'cognitive', 'llm-drills', 'memory'] };
+ expect(isRecDrillRunnable(legacy, 'memory', 'memory-sequence', 'elements-song')).toBe(true);
+ expect(isRecDrillRunnable(legacy, 'morse', 'morse-copy')).toBe(true);
+ expect(isRecDrillRunnable(legacy, 'llm-drills', 'wit-comeback')).toBe(true);
+ expect(isRecDrillRunnable(legacy, 'cognitive', 'n-back')).toBe(true);
+ });
+});
+
describe('getPostRecommendations config filtering (issue #2100)', () => {
it('drops a weakest-skill rec for a drill excluded from session composition', async () => {
// History makes n-back the weakest skill, but the config excludes cognitive
@@ -179,6 +219,54 @@ describe('getPostRecommendations config filtering (issue #2100)', () => {
});
});
+describe('getPostRecommendations topic/item filtering (issue #3252)', () => {
+ const dueItem = (id, title) => ({
+ id, title, type: 'song', content: { chunks: [] },
+ schedule: { ease: 2.5, intervalDays: 1, nextReview: new Date(Date.now() - 86400000).toISOString() },
+ mastery: { overallPct: 40, chunks: {} },
+ });
+
+ it('drops a due memory item the user switched off, keeping its siblings', async () => {
+ state.memoryItems = [dueItem('elements-song', 'The Elements'), dueItem('raven', 'The Raven')];
+ state.config = { memory: { items: { 'elements-song': { enabled: false } } } };
+
+ const { recommendations } = await getPostRecommendations();
+ const dueIds = recommendations.filter(r => r.kind === 'memory-due').map(r => r.id);
+ expect(dueIds).toContain('memory-due:raven');
+ expect(dueIds).not.toContain('memory-due:elements-song');
+ });
+
+ it('a disabled memory TOPIC drops every due item', async () => {
+ state.memoryItems = [dueItem('elements-song', 'The Elements'), dueItem('raven', 'The Raven')];
+ state.config = { topics: { memory: { enabled: false } } };
+
+ const { recommendations } = await getPostRecommendations();
+ expect(recommendations.some(r => r.kind === 'memory-due')).toBe(false);
+ });
+
+ it('keeps every due item under a legacy config with no memory block', async () => {
+ state.memoryItems = [dueItem('elements-song', 'The Elements'), dueItem('raven', 'The Raven')];
+ state.config = {};
+
+ const { recommendations } = await getPostRecommendations();
+ const dueIds = recommendations.filter(r => r.kind === 'memory-due').map(r => r.id);
+ expect(dueIds).toEqual(expect.arrayContaining(['memory-due:elements-song', 'memory-due:raven']));
+ });
+
+ it('suppresses the morse-copy stalled rec when Morse is switched off', async () => {
+ // Mid-Koch progression: the stalled-progression rec fires for a user who has
+ // engaged with Morse and isn't at the final level.
+ state.morse = { kochLevel: 5, kochLevelSet: true, settings: null, rounds: [] };
+ state.config = {};
+ const before = await getPostRecommendations();
+ expect(before.recommendations.some(r => r.drillType === 'morse-copy')).toBe(true);
+
+ state.config = { morse: { enabled: false } };
+ const after = await getPostRecommendations();
+ expect(after.recommendations.some(r => r.drillType === 'morse-copy')).toBe(false);
+ });
+});
+
describe('updatePostConfig goals (issue #2100)', () => {
it('replaces the goals block wholesale so a goal can be cleared', async () => {
state.config = { goals: { streakTarget: 5, dailyMinutes: 20 } };