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

test: harden POST test coverage across stats/adaptive/drill-route/LLM/client scorers (#2102)

[._.]/ Adam Eivyba7f71161f93
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e4bdf09513..d2afb20c77 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -22,6 +22,7 @@
- **Multiplication drills now ramp up instead of starting hard.** The mental-math multiplication drill used to open at a fixed 2-digit × 2-digit difficulty (e.g. `566 × 191`) for everyone. It now climbs a mastery-gated ladder — `1×1` → `1×2` → `1×1×1` → `2×2` → … — starting at single-digit × single-digit and advancing to the next rung only after you answer a level quickly *and* accurately (≥90% correct within a per-rung speed target). The drill header and the config page show your current rung and per-level mastery. On by default; turn off "Progressive difficulty" on the Multiplication card to go back to the manual Max Digits setting.
- **Morse trainer audio now works on mobile Safari.** iOS Safari starts the Web Audio context suspended and only unlocks it once `resume()` fully settles. The trainer fired `resume()` without awaiting it, so the first tones were scheduled against a still-suspended clock and never sounded on iPhone/iPad. It now awaits the resume before scheduling any tone (matching the app's other audio modules), so Copy, Head Copy, and Send-mode keying all produce sound on mobile Safari.
- **The Elements Song trainer is now mobile-friendly and speed-readable.** The periodic-table memorization view no longer overflows off the right edge of a phone screen: the mastery summary, search box, and Mastery/Category toggle now stack and stretch to full width on small screens, the periodic table uses smaller cells (with a scroll-hint fade so it's clear the grid pans horizontally), and the header shrinks to fit. It also gained a **Rapid Read** practice mode that RSVP-flashes the lyrics one word at a time (reusing the app's speed reader) — run the whole song from the Practice list, or tap the gauge icon on any verse to speed-read just that section.
+- **[issue-2102] POST test-coverage hardening.** Added behavioral test coverage for previously-untested load-bearing paths: stats aggregation (module/drill averaging, the days-window cutoff boundary, empty-window shape, streak passthrough), the adaptive-difficulty preview and its integration across every math drill type, the drill-generation route's cache/memory/adaptive dispatch and error paths, all 14 LLM drill generators plus their local/LLM scoring branches, non-memory session scoring/rollup, and the memory-builder's chunk-mastery ordering and built-in mastery-only update restriction. The memory drill's fuzzy-match/fill-blank/sequence/hint scorers and the LLM/session-launcher drill runners' pure helpers are now exported and unit-tested directly instead of only through component rendering (test-only, no user-facing change).
## POST Training
diff --git a/client/src/components/meatspace/post/MemoryPractice.jsx b/client/src/components/meatspace/post/MemoryPractice.jsx
index 970e00a9d5..61156aab9b 100644
--- a/client/src/components/meatspace/post/MemoryPractice.jsx
+++ b/client/src/components/meatspace/post/MemoryPractice.jsx
@@ -276,7 +276,7 @@ export default function MemoryPractice({ item, onBack }) {
ref={inputRef}
value={answer}
onChange={e => setAnswer(e.target.value)}
- onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); checkSpacedAnswer(currentLine.text, currentChunk.id); } }}
+ onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleCheckSpacedAnswer(currentLine.text, currentChunk.id); } }}
placeholder="Type the line..."
className="w-full bg-port-bg border border-port-border rounded-lg px-4 py-3 text-white placeholder-gray-600 focus:border-port-accent focus:outline-none resize-none"
rows={2}
@@ -295,7 +295,7 @@ export default function MemoryPractice({ item, onBack }) {
) : (
<>
<button
- onClick={() => checkSpacedAnswer(currentLine.text, currentChunk.id)}
+ onClick={() => handleCheckSpacedAnswer(currentLine.text, currentChunk.id)}
disabled={!answer.trim()}
className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white rounded-lg transition-colors"
>
@@ -303,7 +303,7 @@ export default function MemoryPractice({ item, onBack }) {
Check
</button>
<button
- onClick={() => { setAnswer(''); checkSpacedAnswer(currentLine.text, currentChunk.id, true); }}
+ onClick={() => { setAnswer(''); handleCheckSpacedAnswer(currentLine.text, currentChunk.id, true); }}
className="px-4 py-2.5 bg-port-card border border-port-border rounded-lg text-gray-400 hover:text-white transition-colors"
>
<SkipForward size={16} />
@@ -417,7 +417,7 @@ export default function MemoryPractice({ item, onBack }) {
ref={inputRef}
value={answer}
onChange={e => setAnswer(e.target.value)}
- onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); checkSequenceAnswer(expectedLine.text); } }}
+ onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleCheckSequenceAnswer(expectedLine.text); } }}
placeholder="Type the next line..."
className="w-full bg-port-bg border border-port-border rounded-lg px-4 py-3 text-white placeholder-gray-600 focus:border-port-accent focus:outline-none resize-none"
rows={2}
@@ -436,7 +436,7 @@ export default function MemoryPractice({ item, onBack }) {
) : (
<>
<button
- onClick={() => checkSequenceAnswer(expectedLine.text)}
+ onClick={() => handleCheckSequenceAnswer(expectedLine.text)}
disabled={!answer.trim()}
className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white rounded-lg transition-colors"
>
@@ -444,7 +444,7 @@ export default function MemoryPractice({ item, onBack }) {
Check
</button>
<button
- onClick={() => { setAnswer(''); checkSequenceAnswer(expectedLine.text, true); }}
+ onClick={() => { setAnswer(''); handleCheckSequenceAnswer(expectedLine.text, true); }}
className="px-4 py-2.5 bg-port-card border border-port-border rounded-lg text-gray-400 hover:text-white transition-colors"
>
<SkipForward size={16} />
@@ -493,7 +493,7 @@ export default function MemoryPractice({ item, onBack }) {
type="text"
value={answer}
onChange={e => setAnswer(e.target.value)}
- onKeyDown={e => { if (e.key === 'Enter') checkFillBlank(blankWords); }}
+ onKeyDown={e => { if (e.key === 'Enter') handleCheckFillBlank(blankWords); }}
placeholder={`${blankWords.length} word${blankWords.length > 1 ? 's' : ''} missing...`}
className="w-full bg-port-bg border border-port-border rounded px-4 py-2.5 text-white placeholder-gray-600 focus:border-port-accent focus:outline-none"
/>
@@ -512,7 +512,7 @@ export default function MemoryPractice({ item, onBack }) {
) : (
<>
<button
- onClick={() => checkFillBlank(blankWords)}
+ onClick={() => handleCheckFillBlank(blankWords)}
disabled={!answer.trim()}
className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white rounded-lg transition-colors"
>
@@ -520,7 +520,7 @@ export default function MemoryPractice({ item, onBack }) {
Check
</button>
<button
- onClick={() => { setAnswer(''); checkFillBlank(blankWords, true); }}
+ onClick={() => { setAnswer(''); handleCheckFillBlank(blankWords, true); }}
className="px-4 py-2.5 bg-port-card border border-port-border rounded-lg text-gray-400 hover:text-white transition-colors"
>
<SkipForward size={16} />
@@ -573,10 +573,10 @@ export default function MemoryPractice({ item, onBack }) {
// --- Helpers ---
- function checkSequenceAnswer(expected, skipped = false) {
- const isCorrect = !skipped && fuzzyMatch(answer, expected);
- setResults(prev => [...prev, { correct: isCorrect, expected, answered: skipped ? '' : answer, element: null }]);
- setShowResult(isCorrect ? 'correct' : 'wrong');
+ function handleCheckSequenceAnswer(expected, skipped = false) {
+ const result = checkSequenceAnswer(answer, expected, skipped);
+ setResults(prev => [...prev, result]);
+ setShowResult(result.correct ? 'correct' : 'wrong');
}
function nextSequenceQuestion() {
@@ -594,17 +594,10 @@ export default function MemoryPractice({ item, onBack }) {
setDone(true);
}
- function checkFillBlank(blankWords, skipped = false) {
- const userWords = skipped ? [] : answer.split(',').map(w => w.trim().toLowerCase());
- const correct = blankWords.every((bw, i) =>
- userWords[i] && userWords[i] === bw.toLowerCase()
- );
- setResults(prev => [...prev, {
- correct,
- expected: blankWords.join(', '),
- answered: skipped ? '' : answer,
- }]);
- setShowResult(correct ? 'correct' : 'wrong');
+ function handleCheckFillBlank(blankWords, skipped = false) {
+ const result = checkFillBlank(answer, blankWords, skipped);
+ setResults(prev => [...prev, result]);
+ setShowResult(result.correct ? 'correct' : 'wrong');
}
function nextFillBlank() {
@@ -618,10 +611,10 @@ export default function MemoryPractice({ item, onBack }) {
}
}
- function checkSpacedAnswer(expected, chunkId, skipped = false) {
- const isCorrect = !skipped && fuzzyMatch(answer, expected);
- setResults(prev => [...prev, { correct: isCorrect, expected, answered: skipped ? '' : answer, chunkId }]);
- setShowResult(isCorrect ? 'correct' : 'wrong');
+ function handleCheckSpacedAnswer(expected, chunkId, skipped = false) {
+ const result = checkSpacedAnswer(answer, expected, chunkId, skipped);
+ setResults(prev => [...prev, result]);
+ setShowResult(result.correct ? 'correct' : 'wrong');
}
function advanceSpaced() {
@@ -682,7 +675,7 @@ export default function MemoryPractice({ item, onBack }) {
* hintLevel 2: show word count only
* hintLevel 3: no hints
*/
-function generateHint(text, hintLevel) {
+export function generateHint(text, hintLevel) {
if (hintLevel >= 3) return null;
const words = text.split(/\s+/);
@@ -797,7 +790,7 @@ function ProgressBar({ current, total }) {
);
}
-function fuzzyMatch(input, expected) {
+export function fuzzyMatch(input, expected) {
const normalize = s => s.toLowerCase().replace(/[,.\-!?'"]/g, '').replace(/\s+/g, ' ').trim();
const a = normalize(input);
const b = normalize(expected);
@@ -809,10 +802,42 @@ function fuzzyMatch(input, expected) {
return matches / bWords.length >= 0.8;
}
-function findChunkForLine(item, lineIndex) {
+export function findChunkForLine(item, lineIndex) {
for (const chunk of item.content?.chunks || []) {
const [start, end] = chunk.lineRange;
if (lineIndex >= start && lineIndex <= end) return chunk.id;
}
return null;
}
+
+// Pure comma-split answer checking for fill-blank mode: multiple acceptable
+// words for the blanks are typed comma-separated and compared in order,
+// case-insensitively. `answer` is passed explicitly (lifted from the
+// component's `answer` state) so this stays free of any React closure —
+// the component's handleCheckFillBlank wrapper is the only caller and owns
+// the setResults/setShowResult side effects.
+export function checkFillBlank(answer, blankWords, skipped = false) {
+ const userWords = skipped ? [] : answer.split(',').map(w => w.trim().toLowerCase());
+ const correct = blankWords.every((bw, i) => userWords[i] && userWords[i] === bw.toLowerCase());
+ return {
+ correct,
+ expected: blankWords.join(', '),
+ answered: skipped ? '' : answer,
+ };
+}
+
+// Pure sequence-recall answer checking: fuzzy-matches the typed answer
+// against the expected next line. `element` is always null here (kept for
+// shape parity with the results list consumed elsewhere).
+export function checkSequenceAnswer(answer, expected, skipped = false) {
+ const isCorrect = !skipped && fuzzyMatch(answer, expected);
+ return { correct: isCorrect, expected, answered: skipped ? '' : answer, element: null };
+}
+
+// Pure spaced-repetition answer checking: fuzzy-matches the typed answer
+// against the expected line, tagging the result with its owning chunk id so
+// per-chunk mastery can be recomputed on save.
+export function checkSpacedAnswer(answer, expected, chunkId, skipped = false) {
+ const isCorrect = !skipped && fuzzyMatch(answer, expected);
+ return { correct: isCorrect, expected, answered: skipped ? '' : answer, chunkId };
+}
diff --git a/client/src/components/meatspace/post/MemoryPractice.test.jsx b/client/src/components/meatspace/post/MemoryPractice.test.jsx
new file mode 100644
index 0000000000..3a8ba7f9af
--- /dev/null
+++ b/client/src/components/meatspace/post/MemoryPractice.test.jsx
@@ -0,0 +1,177 @@
+import { describe, it, expect } from 'vitest';
+import {
+ fuzzyMatch,
+ generateHint,
+ findChunkForLine,
+ checkFillBlank,
+ checkSequenceAnswer,
+ checkSpacedAnswer,
+} from './MemoryPractice';
+
+// Pure-function tests for MemoryPractice's correctness scorers (issue #2102
+// gap #2). These decide whether a memorization drill answer counts as
+// correct — a silent regression here would mis-grade every spaced-repetition
+// / sequence-recall / fill-blank session without failing anywhere visible.
+
+describe('fuzzyMatch', () => {
+ const makeWords = (n) => Array.from({ length: n }, (_, i) => `word${i}`);
+
+ it('returns true for an exact match after normalization', () => {
+ expect(fuzzyMatch('Hello, World!', 'hello world')).toBe(true);
+ });
+
+ it('is case-insensitive and ignores punctuation/extra whitespace', () => {
+ // Note: a hyphen is stripped (not replaced with a space), so hyphenated
+ // words fuse into one token — this case avoids hyphens to isolate the
+ // case/punctuation/whitespace normalization being tested.
+ expect(fuzzyMatch("Don't, Stop! Believing.", 'dont stop believing')).toBe(true);
+ });
+
+ // The issue calls out the 80%-word-match threshold as a specific regression
+ // risk — pin the boundary exactly, both just below and exactly at 0.8.
+ it('matches exactly AT the 0.8 threshold (boundary is inclusive, >=)', () => {
+ const expectedWords = makeWords(100);
+ const expected = expectedWords.join(' ');
+ // 80 of the 100 expected words present -> 80/100 = 0.8 exactly -> true.
+ const input = expectedWords.slice(0, 80).join(' ');
+ expect(fuzzyMatch(input, expected)).toBe(true);
+ });
+
+ it('fails just BELOW the 0.8 threshold', () => {
+ const expectedWords = makeWords(100);
+ const expected = expectedWords.join(' ');
+ // 79 of the 100 expected words present -> 79/100 = 0.79 -> false.
+ const input = expectedWords.slice(0, 79).join(' ');
+ expect(fuzzyMatch(input, expected)).toBe(false);
+ });
+
+ it('matches just ABOVE the 0.8 threshold', () => {
+ const expectedWords = makeWords(100);
+ const expected = expectedWords.join(' ');
+ // 81 of the 100 expected words present -> 81/100 = 0.81 -> true.
+ const input = expectedWords.slice(0, 81).join(' ');
+ expect(fuzzyMatch(input, expected)).toBe(true);
+ });
+
+ it('fails when word overlap is well below the threshold', () => {
+ expect(fuzzyMatch('completely different text', 'the quick brown fox jumps')).toBe(false);
+ });
+});
+
+describe('checkFillBlank', () => {
+ it('marks correct when every comma-separated word matches its blank in order (case-insensitive)', () => {
+ const result = checkFillBlank('Fire, water, earth', ['fire', 'water', 'earth']);
+ expect(result).toEqual({ correct: true, expected: 'fire, water, earth', answered: 'Fire, water, earth' });
+ });
+
+ it('trims whitespace around each comma-separated answer', () => {
+ const result = checkFillBlank(' fire , water , earth ', ['fire', 'water', 'earth']);
+ expect(result.correct).toBe(true);
+ });
+
+ it('marks incorrect when a word is wrong', () => {
+ const result = checkFillBlank('fire, wind, earth', ['fire', 'water', 'earth']);
+ expect(result.correct).toBe(false);
+ });
+
+ it('marks incorrect when fewer answers are given than blanks', () => {
+ const result = checkFillBlank('fire, water', ['fire', 'water', 'earth']);
+ expect(result.correct).toBe(false);
+ });
+
+ it('treats a skipped answer as incorrect with an empty `answered`', () => {
+ const result = checkFillBlank('fire, water, earth', ['fire', 'water', 'earth'], true);
+ expect(result).toEqual({ correct: false, expected: 'fire, water, earth', answered: '' });
+ });
+});
+
+describe('checkSequenceAnswer', () => {
+ it('marks correct when the typed line fuzzy-matches the expected next line', () => {
+ const result = checkSequenceAnswer('the quick brown fox', 'the quick brown fox');
+ expect(result).toEqual({ correct: true, expected: 'the quick brown fox', answered: 'the quick brown fox', element: null });
+ });
+
+ it('marks incorrect when the typed line does not match', () => {
+ const result = checkSequenceAnswer('a totally different line', 'the quick brown fox');
+ expect(result.correct).toBe(false);
+ });
+
+ it('treats a skipped answer as incorrect with an empty `answered`', () => {
+ const result = checkSequenceAnswer('the quick brown fox', 'the quick brown fox', true);
+ expect(result).toEqual({ correct: false, expected: 'the quick brown fox', answered: '', element: null });
+ });
+});
+
+describe('checkSpacedAnswer', () => {
+ it('marks correct when the typed line fuzzy-matches and tags the result with the chunk id', () => {
+ const result = checkSpacedAnswer('the quick brown fox', 'the quick brown fox', 'chunk-1');
+ expect(result).toEqual({ correct: true, expected: 'the quick brown fox', answered: 'the quick brown fox', chunkId: 'chunk-1' });
+ });
+
+ it('marks incorrect when the typed line does not match', () => {
+ const result = checkSpacedAnswer('nothing like it', 'the quick brown fox', 'chunk-1');
+ expect(result.correct).toBe(false);
+ expect(result.chunkId).toBe('chunk-1');
+ });
+
+ it('treats a skipped answer as incorrect with an empty `answered`, still tagged with the chunk id', () => {
+ const result = checkSpacedAnswer('the quick brown fox', 'the quick brown fox', 'chunk-2', true);
+ expect(result).toEqual({ correct: false, expected: 'the quick brown fox', answered: '', chunkId: 'chunk-2' });
+ });
+});
+
+describe('generateHint', () => {
+ const text = 'the quick brown fox';
+
+ it('hintLevel 0 shows first letter + underscores for each word, preserving trailing punctuation', () => {
+ expect(generateHint('the quick, brown fox.', 0)).toBe('t__ q____, b____ f__.');
+ });
+
+ it('hintLevel 0 leaves single-character words untouched', () => {
+ expect(generateHint('a b cat', 0)).toBe('a b c__');
+ });
+
+ it('hintLevel 1 shows first letter of every other word (0-indexed), blanks the rest', () => {
+ expect(generateHint(text, 1)).toBe('t___ ____ b___ ____');
+ });
+
+ it('hintLevel 2 shows only the word count', () => {
+ expect(generateHint(text, 2)).toBe('(4 words)');
+ });
+
+ it('hintLevel 3 (or above) shows no hint at all', () => {
+ expect(generateHint(text, 3)).toBeNull();
+ expect(generateHint(text, 4)).toBeNull();
+ });
+});
+
+describe('findChunkForLine', () => {
+ const item = {
+ content: {
+ chunks: [
+ { id: 'chunk-a', lineRange: [0, 2] },
+ { id: 'chunk-b', lineRange: [3, 5] },
+ ],
+ },
+ };
+
+ it('finds the chunk containing the start of a line range', () => {
+ expect(findChunkForLine(item, 0)).toBe('chunk-a');
+ });
+
+ it('finds the chunk containing the end of a line range (inclusive boundary)', () => {
+ expect(findChunkForLine(item, 2)).toBe('chunk-a');
+ });
+
+ it('finds the next chunk right after the previous one ends', () => {
+ expect(findChunkForLine(item, 3)).toBe('chunk-b');
+ });
+
+ it('returns null when the line index is outside every chunk range', () => {
+ expect(findChunkForLine(item, 99)).toBeNull();
+ });
+
+ it('returns null when there are no chunks', () => {
+ expect(findChunkForLine({ content: {} }, 0)).toBeNull();
+ });
+});
diff --git a/client/src/components/meatspace/post/PostDrillConfig.test.jsx b/client/src/components/meatspace/post/PostDrillConfig.test.jsx
index 37ee9e5009..efd4207fe5 100644
--- a/client/src/components/meatspace/post/PostDrillConfig.test.jsx
+++ b/client/src/components/meatspace/post/PostDrillConfig.test.jsx
@@ -11,23 +11,17 @@ vi.mock('../../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() }
import PostDrillConfig from './PostDrillConfig';
import { updatePostConfig, getProviders, getPostAdaptivePreview, getPostMultiplicationProgress } from '../../../services/api';
-
-// The 14 generatable LLM drill types (mirror server + client constants).
-const ALL_LLM_TYPES = [
- 'pun-wordplay', 'word-association', 'compound-chain', 'bridge-word',
- 'double-meaning', 'idiom-twist', 'story-recall', 'verbal-fluency',
- 'wit-comeback', 'what-if', 'alternative-uses', 'story-prompt',
- 'invention-pitch', 'reframe',
-];
-const LABELS = {
- 'pun-wordplay': 'Pun & Wordplay', 'word-association': 'Word Association',
- 'compound-chain': 'Compound Chain', 'bridge-word': 'Bridge Word',
- 'double-meaning': 'Double Meaning', 'idiom-twist': 'Idiom Twist',
- 'story-recall': 'Story Recall', 'verbal-fluency': 'Verbal Fluency',
- 'wit-comeback': 'Wit & Comeback', 'what-if': 'What If?',
- 'alternative-uses': 'Alternative Uses', 'story-prompt': 'Story Prompt',
- 'invention-pitch': 'Invention Pitch', 'reframe': 'Reframe',
-};
+import { LLM_DRILL_TYPES, DRILL_LABELS } from './constants';
+
+// The generatable LLM drill types + labels, imported from the canonical
+// client constant (mirrors server LLM_DRILL_TYPES in meatspacePostLlm.js) —
+// NOT a hardcoded parallel copy, so this test can't stay green against a
+// stale list if a drill type is ever added/removed/relabeled.
+const ALL_LLM_TYPES = LLM_DRILL_TYPES;
+// The 5 legacy drills that ship enabled by default (server DEFAULT_CONFIG);
+// everything else in ALL_LLM_TYPES is newly-exposed and defaults to opt-in.
+const LEGACY_ENABLED_TYPES = ['pun-wordplay', 'word-association', 'story-recall', 'verbal-fluency', 'wit-comeback'];
+const NEWLY_EXPOSED_TYPES = ALL_LLM_TYPES.filter(t => !LEGACY_ENABLED_TYPES.includes(t));
// Mirrors the server DEFAULT_CONFIG: only the 5 legacy LLM drills ship enabled.
const config = {
@@ -69,7 +63,7 @@ describe('PostDrillConfig', () => {
it('renders a card for every one of the 14 LLM drill types', () => {
render(<PostDrillConfig config={config} onSaved={vi.fn()} onBack={vi.fn()} />);
for (const type of ALL_LLM_TYPES) {
- expect(screen.getByText(LABELS[type])).toBeTruthy();
+ expect(screen.getByText(DRILL_LABELS[type])).toBeTruthy();
}
});
@@ -90,12 +84,11 @@ describe('PostDrillConfig', () => {
// Every type is persisted so the config never silently omits a card the user saw.
expect(Object.keys(saved).sort()).toEqual([...ALL_LLM_TYPES].sort());
// The 5 legacy drills stay enabled...
- for (const t of ['pun-wordplay', 'word-association', 'story-recall', 'verbal-fluency', 'wit-comeback']) {
+ for (const t of LEGACY_ENABLED_TYPES) {
expect(saved[t].enabled).toBe(true);
}
- // ...and the 9 newly-exposed drills default to disabled (opt-in).
- for (const t of ['compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist',
- 'what-if', 'alternative-uses', 'story-prompt', 'invention-pitch', 'reframe']) {
+ // ...and the newly-exposed drills default to disabled (opt-in).
+ for (const t of NEWLY_EXPOSED_TYPES) {
expect(saved[t].enabled).toBe(false);
}
});
diff --git a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx b/client/src/components/meatspace/post/PostLlmDrillRunner.jsx
index 39b6c58cc9..ad468c2818 100644
--- a/client/src/components/meatspace/post/PostLlmDrillRunner.jsx
+++ b/client/src/components/meatspace/post/PostLlmDrillRunner.jsx
@@ -94,27 +94,7 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr
e?.preventDefault();
const responseMs = Date.now() - questionStartRef.current;
- let responseObj;
- if (drillType === 'story-recall') {
- responseObj = {
- questionIndex,
- answers: items.length > 0 ? items : [inputValue.trim()],
- responseMs
- };
- } else if (drillType === 'verbal-fluency' || drillType === 'compound-chain' || drillType === 'alternative-uses') {
- responseObj = {
- questionIndex,
- items: items,
- responseMs
- };
- } else {
- responseObj = {
- questionIndex,
- prompt: currentPrompt?.prompt || currentPrompt?.setup || currentPrompt?.category || currentPrompt?.rootWord || currentPrompt?.word || currentPrompt?.idiom || '',
- response: inputValue.trim(),
- responseMs
- };
- }
+ const responseObj = buildLlmResponseObj({ drillType, questionIndex, items, inputValue, currentPrompt, responseMs });
const newResponses = [...responses, responseObj];
setResponses(newResponses);
@@ -486,7 +466,7 @@ export default function PostLlmDrillRunner({ drill, timeLimitSec, drillIndex, dr
);
}
-function getPrompts(drill) {
+export function getPrompts(drill) {
if (!drill) return [];
switch (drill.type) {
case 'word-association': return drill.questions || [];
@@ -507,6 +487,33 @@ function getPrompts(drill) {
}
}
+// Pure per-type response-object builder — the shape scorePostLlmDrill and the
+// server's finishDrill counterpart key off of. Every shape stamps
+// `questionIndex` so the server can pair a response with its originating
+// prompt/challenge/scenario by explicit index rather than array position —
+// array position broke pairing for hosts (e.g. the standalone WordplayTrainer
+// tab) that submit one response at a time wrapped in a single-item array
+// (fixed in 0a60c8457, "pair wordplay responses with correct challenge by
+// index"). Regressing this field silently mis-scores every response.
+export function buildLlmResponseObj({ drillType, questionIndex, items, inputValue, currentPrompt, responseMs }) {
+ if (drillType === 'story-recall') {
+ return {
+ questionIndex,
+ answers: items.length > 0 ? items : [inputValue.trim()],
+ responseMs,
+ };
+ }
+ if (drillType === 'verbal-fluency' || drillType === 'compound-chain' || drillType === 'alternative-uses') {
+ return { questionIndex, items, responseMs };
+ }
+ return {
+ questionIndex,
+ prompt: currentPrompt?.prompt || currentPrompt?.setup || currentPrompt?.category || currentPrompt?.rootWord || currentPrompt?.word || currentPrompt?.idiom || '',
+ response: inputValue.trim(),
+ responseMs,
+ };
+}
+
// ─────────────────────────────────────────────────────────────────────────────
// DRILL-SPECIFIC UI COMPONENTS
// ─────────────────────────────────────────────────────────────────────────────
diff --git a/client/src/components/meatspace/post/PostLlmDrillRunner.test.jsx b/client/src/components/meatspace/post/PostLlmDrillRunner.test.jsx
index df8865dd09..669ed340a9 100644
--- a/client/src/components/meatspace/post/PostLlmDrillRunner.test.jsx
+++ b/client/src/components/meatspace/post/PostLlmDrillRunner.test.jsx
@@ -5,8 +5,9 @@ vi.mock('../../../services/api', () => ({
scorePostLlmDrill: vi.fn(),
}));
-import PostLlmDrillRunner from './PostLlmDrillRunner';
+import PostLlmDrillRunner, { getPrompts, buildLlmResponseObj } from './PostLlmDrillRunner';
import { scorePostLlmDrill } from '../../../services/api';
+import { LLM_DRILL_TYPES } from './constants';
const noop = () => {};
@@ -133,3 +134,112 @@ describe('PostLlmDrillRunner — training-mode scoring path', () => {
await waitFor(() => expect(screen.getByText('65')).toBeInTheDocument());
});
});
+
+// getPrompts pure-function coverage (issue #2102 gap #9): each of the 14
+// generatable LLM drill types stores its prompt list under a different key
+// (questions/exercises/categories/etc.) — a typo in the switch silently
+// leaves that drill type with zero prompts.
+const TYPE_FIELD = {
+ 'word-association': 'questions',
+ 'story-recall': 'exercises',
+ 'verbal-fluency': 'categories',
+ 'wit-comeback': 'scenarios',
+ 'pun-wordplay': 'challenges',
+ 'compound-chain': 'challenges',
+ 'bridge-word': 'puzzles',
+ 'double-meaning': 'challenges',
+ 'idiom-twist': 'challenges',
+ 'what-if': 'scenarios',
+ 'alternative-uses': 'objects',
+ 'story-prompt': 'prompts',
+ 'invention-pitch': 'problems',
+ 'reframe': 'situations',
+};
+
+describe('getPrompts', () => {
+ it('returns the correct field array for every one of the 14 LLM drill-type shapes', () => {
+ for (const type of LLM_DRILL_TYPES) {
+ const field = TYPE_FIELD[type];
+ const list = [{ id: 'a' }, { id: 'b' }];
+ expect(getPrompts({ type, [field]: list })).toBe(list);
+ }
+ });
+
+ it('returns an empty array when the type-specific field is missing', () => {
+ for (const type of LLM_DRILL_TYPES) {
+ expect(getPrompts({ type })).toEqual([]);
+ }
+ });
+
+ it('returns an empty array for an unrecognized drill type', () => {
+ expect(getPrompts({ type: 'not-a-real-type' })).toEqual([]);
+ });
+
+ it('returns an empty array when drill is null or undefined', () => {
+ expect(getPrompts(null)).toEqual([]);
+ expect(getPrompts(undefined)).toEqual([]);
+ });
+});
+
+// buildLlmResponseObj pure-function coverage (issue #2102 gap #9): every
+// response shape stamps `questionIndex` so the server can pair a response
+// with its originating prompt by explicit index rather than array position
+// (regression fixed in 0a60c8457 — "pair wordplay responses with correct
+// challenge by index"). A dropped/misassigned questionIndex silently
+// mis-scores responses against the wrong prompt.
+describe('buildLlmResponseObj', () => {
+ it('stamps sequential questionIndex values matching each prompt position', () => {
+ const prompts = [{ prompt: 'a' }, { prompt: 'b' }, { prompt: 'c' }];
+ const responses = prompts.map((currentPrompt, questionIndex) =>
+ buildLlmResponseObj({
+ drillType: 'word-association',
+ questionIndex,
+ items: [],
+ inputValue: `answer-${questionIndex}`,
+ currentPrompt,
+ responseMs: 100,
+ })
+ );
+ expect(responses.map(r => r.questionIndex)).toEqual([0, 1, 2]);
+ expect(responses[1]).toMatchObject({ questionIndex: 1, prompt: 'b', response: 'answer-1' });
+ });
+
+ it('story-recall: uses the collected items as answers when present', () => {
+ const result = buildLlmResponseObj({
+ drillType: 'story-recall', questionIndex: 2, items: ['ans1', 'ans2'], inputValue: '', currentPrompt: {}, responseMs: 500,
+ });
+ expect(result).toEqual({ questionIndex: 2, answers: ['ans1', 'ans2'], responseMs: 500 });
+ });
+
+ it('story-recall: falls back to the trimmed inputValue as a single answer when no items were collected', () => {
+ const result = buildLlmResponseObj({
+ drillType: 'story-recall', questionIndex: 0, items: [], inputValue: ' lone answer ', currentPrompt: {}, responseMs: 200,
+ });
+ expect(result).toEqual({ questionIndex: 0, answers: ['lone answer'], responseMs: 200 });
+ });
+
+ it.each(['verbal-fluency', 'compound-chain', 'alternative-uses'])('%s: passes the items array through as-is', (drillType) => {
+ const items = ['x', 'y', 'z'];
+ const result = buildLlmResponseObj({ drillType, questionIndex: 1, items, inputValue: 'ignored', currentPrompt: {}, responseMs: 300 });
+ expect(result).toEqual({ questionIndex: 1, items, responseMs: 300 });
+ });
+
+ it('other types: builds the prompt from the first available field in the fallback chain and trims the response', () => {
+ const result = buildLlmResponseObj({
+ drillType: 'wit-comeback',
+ questionIndex: 3,
+ items: [],
+ inputValue: ' witty reply ',
+ currentPrompt: { setup: 'a setup line' },
+ responseMs: 400,
+ });
+ expect(result).toEqual({ questionIndex: 3, prompt: 'a setup line', response: 'witty reply', responseMs: 400 });
+ });
+
+ it('other types: falls back to an empty prompt string when currentPrompt has none of the known fields', () => {
+ const result = buildLlmResponseObj({
+ drillType: 'what-if', questionIndex: 0, items: [], inputValue: 'x', currentPrompt: {}, responseMs: 0,
+ });
+ expect(result.prompt).toBe('');
+ });
+});
diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsx
index 0be92a27ef..a2a591736d 100644
--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx
+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx
@@ -11,6 +11,28 @@ const streakGlyph = (streak) => (streak >= 7 ? '🔥' : streak >= 3 ? '⚡' : '
const scoreColorClass = (score) =>
score >= 80 ? 'text-port-success' : score >= 50 ? 'text-port-warning' : 'text-port-error';
+// Short "at a glance" summary chip per cognitive drill type, shown next to
+// its label in the launcher sidebar. Pure — no closures over component state.
+export function cognitiveSummary(type, cfg) {
+ if (type === 'n-back') return `${cfg.n ?? 2}-back`;
+ if (type === 'digit-span') return `${cfg.startLength ?? 3}–${cfg.maxLength ?? 8}`;
+ if (type === 'schulte-table') return `${cfg.size ?? 5}×${cfg.size ?? 5}`;
+ if (type === 'reaction-time') return `${cfg.count ?? 15} trials (${cfg.mode ?? 'simple'})`;
+ return cfg.count ? `${cfg.count} trials` : '';
+}
+
+// Pure: sanitizes the optional condition-tags map before submit — drops
+// empty/whitespace-only values so a session with no conditions filled in
+// doesn't persist `{ sleep: '', caffeine: '', stress: '' }` to history.
+// `tags` is passed explicitly (lifted from the component's `tags` state).
+export function buildCleanTags(tags) {
+ const cleanTags = {};
+ for (const [k, v] of Object.entries(tags)) {
+ if (v.trim()) cleanTags[k] = v.trim();
+ }
+ return cleanTags;
+}
+
export default function PostSessionLauncher({ config, recentSessions, stats, statsWeek, onStart, onViewHistory, onViewConfig, onViewMemory, onViewMorse }) {
const [tags, setTags] = useState({ sleep: '', caffeine: '', stress: '' });
const [mode, setMode] = useState('test'); // 'test' | 'train'
@@ -63,24 +85,6 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
choices: cfg.choices,
});
- // Short "at a glance" summary chip per cognitive drill type, shown next to
- // its label in the launcher sidebar.
- function cognitiveSummary(type, cfg) {
- if (type === 'n-back') return `${cfg.n ?? 2}-back`;
- if (type === 'digit-span') return `${cfg.startLength ?? 3}–${cfg.maxLength ?? 8}`;
- if (type === 'schulte-table') return `${cfg.size ?? 5}×${cfg.size ?? 5}`;
- if (type === 'reaction-time') return `${cfg.count ?? 15} trials (${cfg.mode ?? 'simple'})`;
- return cfg.count ? `${cfg.count} trials` : '';
- }
-
- function buildCleanTags() {
- const cleanTags = {};
- for (const [k, v] of Object.entries(tags)) {
- if (v.trim()) cleanTags[k] = v.trim();
- }
- return cleanTags;
- }
-
function handleStart() {
const mathConfigs = enabledMathDrills.map(([type, cfg]) => ({
type,
@@ -113,7 +117,7 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
}));
const drillConfigs = [...mathConfigs, ...llmConfigs, ...cognitiveConfigs];
- onStart(drillConfigs, buildCleanTags(), mode === 'train');
+ onStart(drillConfigs, buildCleanTags(tags), mode === 'train');
}
// Build domain → enabled drills map for quick session
@@ -173,7 +177,7 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
drillConfigs.push(drillConfig);
}
- onStart(drillConfigs, buildCleanTags(), mode === 'train');
+ onStart(drillConfigs, buildCleanTags(tags), mode === 'train');
}
// Focused practice on a single domain: run every enabled drill in that domain
@@ -213,7 +217,7 @@ export default function PostSessionLauncher({ config, recentSessions, stats, sta
}
return drillConfig;
});
- onStart(drillConfigs, buildCleanTags(), mode === 'train');
+ onStart(drillConfigs, buildCleanTags(tags), mode === 'train');
}
const hasAnyDrills = enabledMathDrills.length > 0 || enabledLlmDrills.length > 0 || enabledCognitiveDrills.length > 0;
diff --git a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx b/client/src/components/meatspace/post/PostSessionLauncher.test.jsx
new file mode 100644
index 0000000000..efea2c5389
--- /dev/null
+++ b/client/src/components/meatspace/post/PostSessionLauncher.test.jsx
@@ -0,0 +1,63 @@
+import { describe, it, expect } from 'vitest';
+import { buildCleanTags, cognitiveSummary } from './PostSessionLauncher';
+
+// Pure-function tests for PostSessionLauncher's pre-submit helpers (issue
+// #2102 gap #10). Both were lifted from component-body closures to module
+// scope with explicit parameters (`tags` for buildCleanTags) so they can be
+// tested directly without rendering the launcher or its provider fetch.
+
+describe('buildCleanTags', () => {
+ it('keeps a filled-in value, trimmed', () => {
+ expect(buildCleanTags({ sleep: ' good ', caffeine: '', stress: '' })).toEqual({ sleep: 'good' });
+ });
+
+ it('drops empty-string values', () => {
+ expect(buildCleanTags({ sleep: '', caffeine: '', stress: '' })).toEqual({});
+ });
+
+ it('drops whitespace-only values', () => {
+ expect(buildCleanTags({ sleep: ' ', caffeine: '\t', stress: '' })).toEqual({});
+ });
+
+ it('keeps multiple filled-in values, each trimmed independently', () => {
+ expect(buildCleanTags({ sleep: 'poor', caffeine: ' 2 cups ', stress: 'high' })).toEqual({
+ sleep: 'poor',
+ caffeine: '2 cups',
+ stress: 'high',
+ });
+ });
+
+ it('returns an empty object for an empty tags map', () => {
+ expect(buildCleanTags({})).toEqual({});
+ });
+});
+
+describe('cognitiveSummary', () => {
+ it('summarizes n-back as "<n>-back", defaulting n to 2', () => {
+ expect(cognitiveSummary('n-back', {})).toBe('2-back');
+ expect(cognitiveSummary('n-back', { n: 3 })).toBe('3-back');
+ });
+
+ it('summarizes digit-span as a start–max length range, defaulting to 3–8', () => {
+ expect(cognitiveSummary('digit-span', {})).toBe('3–8');
+ expect(cognitiveSummary('digit-span', { startLength: 4, maxLength: 9 })).toBe('4–9');
+ });
+
+ it('summarizes schulte-table as a size×size grid, defaulting to 5×5', () => {
+ expect(cognitiveSummary('schulte-table', {})).toBe('5×5');
+ expect(cognitiveSummary('schulte-table', { size: 6 })).toBe('6×6');
+ });
+
+ it('summarizes reaction-time as trial count + mode, defaulting to 15 trials (simple)', () => {
+ expect(cognitiveSummary('reaction-time', {})).toBe('15 trials (simple)');
+ expect(cognitiveSummary('reaction-time', { count: 20, mode: 'choice' })).toBe('20 trials (choice)');
+ });
+
+ it('falls back to "<count> trials" for an unrecognized type with a count', () => {
+ expect(cognitiveSummary('stroop', { count: 10 })).toBe('10 trials');
+ });
+
+ it('falls back to an empty string for an unrecognized type with no count', () => {
+ expect(cognitiveSummary('mental-rotation', {})).toBe('');
+ });
+});
diff --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.js
index 8a147714ae..f6e7de8211 100644
--- a/server/lib/postValidation.test.js
+++ b/server/lib/postValidation.test.js
@@ -1,5 +1,15 @@
import { describe, it, expect } from 'vitest';
-import { postLlmScoreRequestSchema, postConfigUpdateSchema, postSessionSubmitSchema, postDrillRequestSchema, trainingEntrySchema, LLM_DRILL_TYPES } from './postValidation.js';
+import {
+ postLlmScoreRequestSchema,
+ postConfigUpdateSchema,
+ postSessionSubmitSchema,
+ postDrillRequestSchema,
+ trainingEntrySchema,
+ memoryItemCreateSchema,
+ memoryScheduleSchema,
+ memoryPracticeSchema,
+ LLM_DRILL_TYPES,
+} from './postValidation.js';
describe('postConfigUpdateSchema llmDrills', () => {
// Regression: the config UI (PostDrillConfig.jsx) exposed only 5 of the 14
@@ -206,3 +216,133 @@ describe('postLlmScoreRequestSchema', () => {
})).toThrow();
});
});
+
+// =============================================================================
+// drillTypeConfigSchema numeric bounds (via postDrillRequestSchema.config)
+// (issue #2102 notes)
+// =============================================================================
+
+describe('drillTypeConfigSchema numeric bounds', () => {
+ it('accepts math-drill knobs within their documented bounds', () => {
+ const parsed = postDrillRequestSchema.parse({
+ type: 'serial-subtraction',
+ config: { steps: 50, subtrahend: 100, maxDigits: 4, tolerancePct: 50 },
+ });
+ expect(parsed.config).toMatchObject({ steps: 50, subtrahend: 100, maxDigits: 4, tolerancePct: 50 });
+ });
+
+ it('rejects steps above the max (50) and below the min (1)', () => {
+ expect(() => postDrillRequestSchema.parse({ type: 'serial-subtraction', config: { steps: 51 } })).toThrow();
+ expect(() => postDrillRequestSchema.parse({ type: 'serial-subtraction', config: { steps: 0 } })).toThrow();
+ });
+
+ it('rejects maxDigits outside 1-4', () => {
+ expect(() => postDrillRequestSchema.parse({ type: 'multiplication', config: { maxDigits: 5 } })).toThrow();
+ expect(() => postDrillRequestSchema.parse({ type: 'multiplication', config: { maxDigits: 0 } })).toThrow();
+ });
+
+ it('rejects tolerancePct outside 1-50', () => {
+ expect(() => postDrillRequestSchema.parse({ type: 'estimation', config: { tolerancePct: 0 } })).toThrow();
+ expect(() => postDrillRequestSchema.parse({ type: 'estimation', config: { tolerancePct: 51 } })).toThrow();
+ });
+
+ it('accepts cognitive-drill knobs within bounds (n, length, size, choices)', () => {
+ const parsed = postDrillRequestSchema.parse({
+ type: 'n-back',
+ config: { n: 3, length: 60, size: 7, choices: 4 },
+ });
+ expect(parsed.config).toMatchObject({ n: 3, length: 60, size: 7, choices: 4 });
+ });
+
+ it('rejects an out-of-range n-back n (must be 1-3)', () => {
+ expect(() => postDrillRequestSchema.parse({ type: 'n-back', config: { n: 4 } })).toThrow();
+ expect(() => postDrillRequestSchema.parse({ type: 'n-back', config: { n: 0 } })).toThrow();
+ });
+
+ it('rejects an out-of-range schulte-table size (must be 3-7)', () => {
+ expect(() => postDrillRequestSchema.parse({ type: 'schulte-table', config: { size: 8 } })).toThrow();
+ expect(() => postDrillRequestSchema.parse({ type: 'schulte-table', config: { size: 2 } })).toThrow();
+ });
+});
+
+// =============================================================================
+// memoryScheduleSchema / memoryItemCreateSchema ease bounds (issue #2102 notes)
+// =============================================================================
+
+describe('memoryScheduleSchema ease bounds', () => {
+ it('accepts ease within the SM-2 bounds [1.3, 5]', () => {
+ expect(memoryScheduleSchema.parse({ ease: 1.3, intervalDays: 0, nextReview: '2026-07-01T00:00:00.000Z' }).ease).toBe(1.3);
+ expect(memoryScheduleSchema.parse({ ease: 5, intervalDays: 10, nextReview: '2026-07-01T00:00:00.000Z' }).ease).toBe(5);
+ });
+
+ it('rejects ease below 1.3 or above 5', () => {
+ expect(() => memoryScheduleSchema.parse({ ease: 1.2, intervalDays: 0, nextReview: '2026-07-01T00:00:00.000Z' })).toThrow();
+ expect(() => memoryScheduleSchema.parse({ ease: 5.1, intervalDays: 0, nextReview: '2026-07-01T00:00:00.000Z' })).toThrow();
+ });
+
+ it('rejects a negative intervalDays', () => {
+ expect(() => memoryScheduleSchema.parse({ ease: 2.5, intervalDays: -1, nextReview: '2026-07-01T00:00:00.000Z' })).toThrow();
+ });
+});
+
+describe('memoryItemCreateSchema', () => {
+ it('accepts a well-formed create request with an embedded schedule', () => {
+ const parsed = memoryItemCreateSchema.parse({
+ title: 'My Poem',
+ type: 'poem',
+ lines: ['line one', 'line two'],
+ schedule: { ease: 2.5, intervalDays: 1, nextReview: '2026-07-01T00:00:00.000Z' },
+ });
+ expect(parsed.schedule.ease).toBe(2.5);
+ expect(parsed.type).toBe('poem');
+ });
+
+ it('rejects an out-of-bounds embedded schedule ease (schema parity with memoryScheduleSchema)', () => {
+ expect(() => memoryItemCreateSchema.parse({
+ title: 'My Poem',
+ lines: ['line one'],
+ schedule: { ease: 10, intervalDays: 1, nextReview: '2026-07-01T00:00:00.000Z' },
+ })).toThrow();
+ });
+
+ it('rejects an empty lines array', () => {
+ expect(() => memoryItemCreateSchema.parse({ title: 'Empty', lines: [] })).toThrow();
+ });
+
+ it('rejects an unknown item type', () => {
+ expect(() => memoryItemCreateSchema.parse({ title: 'X', type: 'novel', lines: ['a'] })).toThrow();
+ });
+
+ it('defaults type to "text" when omitted', () => {
+ expect(memoryItemCreateSchema.parse({ title: 'X', lines: ['a'] }).type).toBe('text');
+ });
+});
+
+// =============================================================================
+// memoryPracticeSchema mode enums (issue #2102 notes)
+// =============================================================================
+
+describe('memoryPracticeSchema mode enums', () => {
+ it('accepts every documented practice mode', () => {
+ for (const mode of ['fill-blank', 'sequence', 'element-flash', 'learn', 'speed-run']) {
+ const parsed = memoryPracticeSchema.parse({ mode, results: [{ correct: true }] });
+ expect(parsed.mode).toBe(mode);
+ }
+ });
+
+ it('rejects an unknown practice mode', () => {
+ expect(() => memoryPracticeSchema.parse({ mode: 'not-a-mode', results: [{ correct: true }] })).toThrow();
+ });
+
+ it('rejects an empty results array', () => {
+ expect(() => memoryPracticeSchema.parse({ mode: 'fill-blank', results: [] })).toThrow();
+ });
+
+ it('accepts a nullable chunkId and optional totalMs', () => {
+ const parsed = memoryPracticeSchema.parse({
+ mode: 'sequence', chunkId: null, results: [{ correct: false, expected: 'x', answered: 'y' }], totalMs: 4000,
+ });
+ expect(parsed.chunkId).toBeNull();
+ expect(parsed.totalMs).toBe(4000);
+ });
+});
diff --git a/server/routes/meatspacePostRoutes.drill.test.js b/server/routes/meatspacePostRoutes.drill.test.js
new file mode 100644
index 0000000000..76b889cdf2
--- /dev/null
+++ b/server/routes/meatspacePostRoutes.drill.test.js
@@ -0,0 +1,200 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+
+// Scoped to the busiest untested handler: POST /post/drill (issue #2102 gap 4).
+// Mock every service the route dispatches to so this file exercises ONLY the
+// route's own branching (LLM cache-first, memory- prefix-strip dispatch,
+// adaptive/progression attachment on math, and the three ServerError throws) —
+// the services themselves already have dedicated unit coverage elsewhere.
+vi.mock('../services/meatspacePostDrillCache.js', () => ({
+ // postValidation.js's postDrillCacheFillSchema enum-validates against this.
+ CACHEABLE_TYPES: ['compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist'],
+ getCacheStats: vi.fn(() => ({})),
+ requestCacheFill: vi.fn(),
+ getCachedDrill: vi.fn(() => null),
+ triggerReplenish: vi.fn(),
+}));
+
+vi.mock('../services/meatspacePostLlm.js', () => ({
+ generateLlmDrill: vi.fn(),
+ scoreLlmDrill: vi.fn(),
+}));
+
+vi.mock('../services/meatspacePostMemory.js', () => ({
+ generateMemoryDrill: vi.fn(),
+}));
+
+vi.mock('../services/meatspacePost.js', () => ({
+ resolveDrillConfig: vi.fn(),
+ generateDrill: vi.fn(),
+}));
+
+import { getCachedDrill, triggerReplenish } from '../services/meatspacePostDrillCache.js';
+import { generateLlmDrill } from '../services/meatspacePostLlm.js';
+import { generateMemoryDrill } from '../services/meatspacePostMemory.js';
+import { resolveDrillConfig, generateDrill } from '../services/meatspacePost.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import meatspacePostRoutes from './meatspacePostRoutes.js';
+
+function makeApp() {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/meatspace', meatspacePostRoutes);
+ app.use(errorMiddleware);
+ return app;
+}
+
+describe('POST /api/meatspace/post/drill', () => {
+ let app;
+ beforeEach(() => {
+ app = makeApp();
+ vi.clearAllMocks();
+ });
+
+ // ===========================================================================
+ // LLM drill types — cache-first branch
+ // ===========================================================================
+
+ describe('LLM drill types', () => {
+ it('serves from cache when a pre-generated drill is available, and triggers a replenish', async () => {
+ const cached = { type: 'word-association', config: { count: 5 }, questions: [{ prompt: 'cathedral' }] };
+ getCachedDrill.mockReturnValue(cached);
+
+ const r = await request(app).post('/api/meatspace/post/drill')
+ .send({ type: 'word-association', config: {}, providerId: 'prov-1', model: 'model-1' });
+
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual(cached);
+ expect(getCachedDrill).toHaveBeenCalledWith('word-association');
+ expect(triggerReplenish).toHaveBeenCalledWith('word-association', 'prov-1', 'model-1');
+ expect(generateLlmDrill).not.toHaveBeenCalled();
+ });
+
+ it('falls through to live generation on a cold cache, and still triggers a replenish', async () => {
+ getCachedDrill.mockReturnValue(null);
+ const generated = { type: 'word-association', config: { count: 5 }, questions: [{ prompt: 'river' }] };
+ generateLlmDrill.mockResolvedValue(generated);
+
+ const r = await request(app).post('/api/meatspace/post/drill')
+ .send({ type: 'word-association', config: { count: 5 } });
+
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual(generated);
+ expect(generateLlmDrill).toHaveBeenCalledWith('word-association', { count: 5 }, undefined, undefined);
+ expect(triggerReplenish).toHaveBeenCalledWith('word-association', undefined, undefined);
+ });
+
+ it('throws LLM_DRILL_FAILED when generation returns nothing', async () => {
+ getCachedDrill.mockReturnValue(null);
+ generateLlmDrill.mockResolvedValue(null);
+
+ const r = await request(app).post('/api/meatspace/post/drill').send({ type: 'word-association', config: {} });
+
+ expect(r.status).toBe(500);
+ expect(r.body.code).toBe('LLM_DRILL_FAILED');
+ expect(triggerReplenish).not.toHaveBeenCalled();
+ });
+ });
+
+ // ===========================================================================
+ // Memory drill types — `memory-` prefix-strip dispatch
+ // ===========================================================================
+
+ 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: [] };
+ generateMemoryDrill.mockResolvedValue(drill);
+
+ 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' });
+ });
+
+ it('throws MEMORY_DRILL_FAILED when no drill can be generated', async () => {
+ generateMemoryDrill.mockResolvedValue(null);
+
+ const r = await request(app).post('/api/meatspace/post/drill')
+ .send({ type: 'memory-element-flash', config: {} });
+
+ expect(r.status).toBe(500);
+ expect(r.body.code).toBe('MEMORY_DRILL_FAILED');
+ });
+ });
+
+ // ===========================================================================
+ // Math / cognitive drill types — adaptive + progressive-ladder attachment
+ // ===========================================================================
+
+ describe('Math/cognitive drill types', () => {
+ it('generates via the resolved effective config and attaches an adaptive explainer when present', async () => {
+ resolveDrillConfig.mockResolvedValue({
+ config: { steps: 10 },
+ adaptive: { applied: true, reason: 'harder', field: 'steps' },
+ progression: null,
+ });
+ generateDrill.mockReturnValue({ type: 'doubling-chain', config: { steps: 10 }, questions: [{ prompt: '4 x 2', expected: 8 }] });
+
+ const r = await request(app).post('/api/meatspace/post/drill')
+ .send({ type: 'doubling-chain', config: { steps: 8 } });
+
+ expect(r.status).toBe(200);
+ expect(resolveDrillConfig).toHaveBeenCalledWith('doubling-chain', { steps: 8 });
+ expect(generateDrill).toHaveBeenCalledWith('doubling-chain', { steps: 10 });
+ expect(r.body.adaptive).toEqual({ applied: true, reason: 'harder', field: 'steps' });
+ expect(r.body.progression).toBeUndefined();
+ });
+
+ it('attaches a progression explainer for the progressive multiplication ladder', async () => {
+ resolveDrillConfig.mockResolvedValue({
+ config: { count: 10, level: 1, factors: [1, 2] },
+ adaptive: null,
+ progression: { level: 1, floorLevel: 1 },
+ });
+ generateDrill.mockReturnValue({ type: 'multiplication', config: { level: 1 }, questions: [] });
+
+ const r = await request(app).post('/api/meatspace/post/drill')
+ .send({ type: 'multiplication', config: { count: 10 } });
+
+ expect(r.status).toBe(200);
+ expect(r.body.progression).toEqual({ level: 1, floorLevel: 1 });
+ expect(r.body.adaptive).toBeUndefined();
+ });
+
+ it('omits both explainers when neither adaptive nor progression ran', async () => {
+ resolveDrillConfig.mockResolvedValue({ config: { steps: 8 }, adaptive: null });
+ generateDrill.mockReturnValue({ type: 'doubling-chain', config: { steps: 8 }, questions: [] });
+
+ const r = await request(app).post('/api/meatspace/post/drill')
+ .send({ type: 'doubling-chain', config: {} });
+
+ expect(r.status).toBe(200);
+ expect(r.body.adaptive).toBeUndefined();
+ expect(r.body.progression).toBeUndefined();
+ });
+
+ it('throws INVALID_DRILL_TYPE when the generator returns nothing for a recognized-but-unhandled type', async () => {
+ resolveDrillConfig.mockResolvedValue({ config: {}, adaptive: null });
+ generateDrill.mockReturnValue(null);
+
+ const r = await request(app).post('/api/meatspace/post/drill')
+ .send({ type: 'n-back', config: {} });
+
+ expect(r.status).toBe(400);
+ expect(r.body.code).toBe('INVALID_DRILL_TYPE');
+ });
+ });
+
+ // ===========================================================================
+ // Request validation
+ // ===========================================================================
+
+ it('rejects an unknown drill type at the validation layer', async () => {
+ const r = await request(app).post('/api/meatspace/post/drill').send({ type: 'not-a-real-type', config: {} });
+ expect(r.status).toBe(400);
+ expect(resolveDrillConfig).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.js
index 7a26b5d11c..479abb382c 100644
--- a/server/services/meatspacePost.test.js
+++ b/server/services/meatspacePost.test.js
@@ -29,6 +29,7 @@ import {
resolveDrillConfig,
getMultiplicationProgress,
getPostStats,
+ getAdaptivePreview,
deriveTaskAccuracy,
deriveTaskCompletion,
} from './meatspacePost.js';
@@ -1010,3 +1011,340 @@ describe('adaptive signal is accuracy-driven — fast-sloppy vs slow-accurate di
expect(adaptive.applied).toBe(false);
});
});
+
+// =============================================================================
+// getPostStats — byModule averaging, days-window cutoff, empty-window shape,
+// streak passthrough (issue #2102 gap 1)
+// =============================================================================
+
+describe('getPostStats — byModule averaging, days window cutoff, empty-window shape', () => {
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ function mockSessions(sessions) {
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ if (String(path).includes('post-sessions')) return Promise.resolve({ sessions });
+ return Promise.resolve(defaultValue);
+ });
+ }
+
+ it('averages and rounds byModule scores across multiple tasks in a session', async () => {
+ const today = new Date().toISOString().split('T')[0];
+ mockSessions([
+ {
+ date: today, score: 68,
+ tasks: [
+ { module: 'mental-math', type: 'doubling-chain', score: 60 },
+ { module: 'mental-math', type: 'multiplication', score: 75 },
+ ],
+ },
+ ]);
+ const stats = await getPostStats(30);
+ // (60 + 75) / 2 = 67.5 — JS Math.round rounds .5 up to 68.
+ expect(stats.byModule['mental-math']).toBe(68);
+ });
+
+ it('includes a session dated exactly at the cutoff boundary (s.date >= cutoff), excludes the day before', async () => {
+ const days = 5;
+ const cutoff = new Date();
+ cutoff.setDate(cutoff.getDate() - days);
+ const cutoffStr = cutoff.toISOString().split('T')[0];
+ const [y, m, d] = cutoffStr.split('-').map(Number);
+ const dayBeforeStr = new Date(Date.UTC(y, m - 1, d) - 86400000).toISOString().split('T')[0];
+
+ mockSessions([
+ { date: cutoffStr, score: 100, tasks: [{ module: 'mental-math', type: 'doubling-chain', score: 100 }] },
+ { date: dayBeforeStr, score: 0, tasks: [{ module: 'mental-math', type: 'doubling-chain', score: 0 }] },
+ ]);
+ const stats = await getPostStats(days);
+ expect(stats.sessionCount).toBe(1);
+ expect(stats.overall).toBe(100);
+ });
+
+ it('returns the zeroed empty-window shape when nothing falls inside the window, but streaks still pass through from all-time history', async () => {
+ const oldDate = new Date(Date.now() - 90 * 86400000).toISOString().split('T')[0];
+ mockSessions([
+ { date: oldDate, score: 50, tasks: [{ module: 'mental-math', type: 'doubling-chain', score: 50 }] },
+ ]);
+ const stats = await getPostStats(5);
+ expect(stats.sessionCount).toBe(0);
+ expect(stats.overall).toBeNull();
+ expect(stats.byModule).toEqual({});
+ expect(stats.byDrill).toEqual({});
+ expect(stats.byDrillCount).toEqual({});
+ expect(stats.byDrillAccuracy).toEqual({});
+ expect(stats.byDrillCompletion).toEqual({});
+ // Streaks are computed over ALL history, independent of the stats window —
+ // the empty-window branch must still spread them onto the result.
+ expect(stats.lastDate).toBe(oldDate);
+ expect(stats.completedToday).toBe(false);
+ });
+
+ it('passes streak fields through unchanged alongside a non-empty window', async () => {
+ const today = new Date().toISOString().split('T')[0];
+ mockSessions([
+ { date: today, score: 80, tasks: [{ module: 'mental-math', type: 'doubling-chain', score: 80 }] },
+ ]);
+ const stats = await getPostStats(30);
+ expect(stats.completedToday).toBe(true);
+ expect(stats.currentStreak).toBe(1);
+ expect(stats.todayScore).toBe(80);
+ });
+});
+
+// =============================================================================
+// resolveDrillConfig / getAdaptivePreview — adaptive integration across ALL
+// math drill types (issue #2102 gap 3). The pure `adaptDrillConfig` policy is
+// already exhaustively covered in postAdaptive.test.js; these tests exercise
+// the INTEGRATION — real scored session history flowing through getPostStats
+// -> getAdaptiveSignal -> resolveDrillConfig/getAdaptivePreview — for the
+// three types that previously only had multiplication/doubling-chain covered.
+// =============================================================================
+
+describe('resolveDrillConfig — adaptive integration for serial-subtraction/powers/estimation', () => {
+ const today = new Date().toISOString().split('T')[0];
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ function mockAdaptiveSessions(type, accuracy, count = 3) {
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ const p = String(path);
+ if (p.includes('post-sessions')) {
+ return Promise.resolve({
+ sessions: [{
+ date: today,
+ score: 55,
+ tasks: Array.from({ length: count }, () => ({
+ module: 'mental-math', type, score: 55, accuracy, completion: 1, questions: [],
+ })),
+ }],
+ });
+ }
+ if (p.includes('post-config')) return Promise.resolve({ adaptive: { enabled: true } });
+ return Promise.resolve(defaultValue);
+ });
+ }
+
+ it('serial-subtraction: sustained high accuracy nudges MORE steps (harder)', async () => {
+ mockAdaptiveSessions('serial-subtraction', 1);
+ const { adaptive, config } = await resolveDrillConfig('serial-subtraction', { steps: 10 });
+ expect(adaptive.reason).toBe('harder');
+ expect(config.steps).toBeGreaterThan(10);
+ });
+
+ it('serial-subtraction: sustained low accuracy nudges FEWER steps (easier)', async () => {
+ mockAdaptiveSessions('serial-subtraction', 0);
+ const { adaptive, config } = await resolveDrillConfig('serial-subtraction', { steps: 10 });
+ expect(adaptive.reason).toBe('easier');
+ expect(config.steps).toBeLessThan(10);
+ });
+
+ it('powers: sustained high accuracy nudges a HIGHER max exponent (harder)', async () => {
+ mockAdaptiveSessions('powers', 1);
+ const { adaptive, config } = await resolveDrillConfig('powers', { maxExponent: 10 });
+ expect(adaptive.reason).toBe('harder');
+ expect(config.maxExponent).toBeGreaterThan(10);
+ });
+
+ it('powers: sustained low accuracy nudges a LOWER max exponent (easier)', async () => {
+ mockAdaptiveSessions('powers', 0);
+ const { adaptive, config } = await resolveDrillConfig('powers', { maxExponent: 10 });
+ expect(adaptive.reason).toBe('easier');
+ expect(config.maxExponent).toBeLessThan(10);
+ });
+
+ it('estimation: sustained high accuracy TIGHTENS tolerance (lower % = harder)', async () => {
+ mockAdaptiveSessions('estimation', 1);
+ const { adaptive, config } = await resolveDrillConfig('estimation', { tolerancePct: 10 });
+ expect(adaptive.reason).toBe('harder');
+ expect(config.tolerancePct).toBeLessThan(10);
+ });
+
+ it('estimation: sustained low accuracy WIDENS tolerance (higher % = easier)', async () => {
+ mockAdaptiveSessions('estimation', 0);
+ const { adaptive, config } = await resolveDrillConfig('estimation', { tolerancePct: 10 });
+ expect(adaptive.reason).toBe('easier');
+ expect(config.tolerancePct).toBeGreaterThan(10);
+ });
+
+ it('holds under the sample gate even with a perfect accuracy signal', async () => {
+ mockAdaptiveSessions('serial-subtraction', 1, 2); // 2 samples, gate is minSamples=3
+ const { adaptive, config } = await resolveDrillConfig('serial-subtraction', { steps: 10 });
+ expect(adaptive.reason).toBe('insufficient-samples');
+ expect(adaptive.applied).toBe(false);
+ expect(config.steps).toBe(10);
+ });
+});
+
+describe('getAdaptivePreview', () => {
+ const today = new Date().toISOString().split('T')[0];
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ it('reports enabled:false and leaves every drill unapplied when the Adaptive toggle is off', async () => {
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ const p = String(path);
+ if (p.includes('post-sessions')) return Promise.resolve({ sessions: [] });
+ if (p.includes('post-config')) return Promise.resolve({ adaptive: { enabled: false } });
+ return Promise.resolve(defaultValue);
+ });
+ const preview = await getAdaptivePreview();
+ expect(preview.enabled).toBe(false);
+ expect(preview.windowDays).toBeGreaterThan(0);
+ expect(preview.thresholds.minSamples).toBeGreaterThan(0);
+ expect(Object.keys(preview.drills)).toEqual(
+ expect.arrayContaining(['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation'])
+ );
+ });
+
+ it('previews the effective per-type nudge from recent scored performance when enabled', async () => {
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ const p = String(path);
+ if (p.includes('post-sessions')) {
+ return Promise.resolve({
+ sessions: [{
+ date: today,
+ score: 55,
+ tasks: Array.from({ length: 3 }, () => ({
+ module: 'mental-math', type: 'multiplication', score: 55, accuracy: 1, completion: 1, questions: [],
+ })),
+ }],
+ });
+ }
+ if (p.includes('post-config')) {
+ return Promise.resolve({
+ adaptive: { enabled: true },
+ mentalMath: { drillTypes: { multiplication: { maxDigits: 2 } } },
+ });
+ }
+ return Promise.resolve(defaultValue);
+ });
+ const preview = await getAdaptivePreview();
+ expect(preview.enabled).toBe(true);
+ expect(preview.drills.multiplication.reason).toBe('harder');
+ expect(preview.drills.multiplication.config.maxDigits).toBe(3);
+ // A type with no recent samples falls back to "not enough signal yet".
+ expect(preview.drills['doubling-chain'].reason).toBe('insufficient-samples');
+ });
+});
+
+// =============================================================================
+// submitPostSession — non-memory task types recomputed server-side, session
+// score rollup, and persistence (issue #2102 gap 7). The memory-drill branch
+// is already covered above; this covers math/cognitive/LLM.
+// =============================================================================
+
+describe('submitPostSession — non-memory task types', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ const p = String(path);
+ if (p.includes('post-sessions')) return Promise.resolve({ sessions: [] });
+ if (p.includes('post-memory-items')) return Promise.resolve({ items: [] });
+ return Promise.resolve(defaultValue); // post-config.json -> baseDefaults clone
+ });
+ });
+
+ it('rescores a math task server-side, ignoring client-tampered expected/correct', async () => {
+ const session = await submitPostSession({
+ cadence: 'daily',
+ modules: ['mental-math'],
+ tasks: [{
+ module: 'mental-math',
+ type: 'doubling-chain',
+ config: { startValue: 4, steps: 2 },
+ questions: [
+ { prompt: '4 x 2', expected: 999, answered: 8, correct: false, responseMs: 500 },
+ { prompt: '8 x 2', expected: 999, answered: 16, correct: false, responseMs: 500 },
+ ],
+ totalMs: 1000,
+ }],
+ tags: {},
+ });
+
+ const task = session.tasks[0];
+ expect(task.questions[0].expected).toBe(8);
+ expect(task.questions[0].correct).toBe(true);
+ expect(task.accuracy).toBe(1);
+ expect(task.score).toBeGreaterThan(0);
+ });
+
+ it('rescores a cognitive task server-side via scoreCognitiveDrill, ignoring client score', async () => {
+ const drillData = {
+ type: 'digit-span',
+ config: { direction: 'forward', maxLength: 5 },
+ sequences: [{ digits: [1, 2, 3], length: 3 }],
+ };
+ const session = await submitPostSession({
+ cadence: 'daily',
+ modules: ['cognitive'],
+ tasks: [{
+ module: 'cognitive',
+ type: 'digit-span',
+ drillData,
+ questions: [{ index: 0, answered: '123', responseMs: 1000 }],
+ score: 0, // client-sent score must be ignored — server recomputes via the answer key
+ totalMs: 1000,
+ }],
+ tags: {},
+ });
+
+ const task = session.tasks[0];
+ expect(task.questions[0].correct).toBe(true);
+ expect(task.score).toBeGreaterThan(0);
+ });
+
+ it('trusts the client-computed score for LLM drill tasks (never re-scored server-side)', async () => {
+ const session = await submitPostSession({
+ cadence: 'daily',
+ modules: ['llm-drills'],
+ tasks: [{
+ module: 'llm-drills',
+ type: 'word-association',
+ responses: [{ questionIndex: 0, response: 'church', responseMs: 3000, llmScore: 90 }],
+ score: 87,
+ totalMs: 3000,
+ }],
+ tags: {},
+ });
+ expect(session.tasks[0].score).toBe(87);
+ });
+
+ it('rolls up the session score as the mean of all task scores', async () => {
+ const session = await submitPostSession({
+ cadence: 'daily',
+ modules: ['mental-math', 'llm-drills'],
+ tasks: [
+ {
+ module: 'mental-math', type: 'doubling-chain',
+ config: { startValue: 4, steps: 1 },
+ questions: [{ prompt: '4 x 2', answered: 8, responseMs: 500 }],
+ totalMs: 500,
+ },
+ { module: 'llm-drills', type: 'word-association', responses: [], score: 50, totalMs: 1000 },
+ ],
+ tags: {},
+ });
+ const expectedMean = Math.round((session.tasks[0].score + 50) / 2);
+ expect(session.score).toBe(expectedMean);
+ });
+
+ it('persists the computed session via atomicWrite with the durationMs/tags rollup', async () => {
+ await submitPostSession({
+ cadence: 'daily',
+ modules: ['mental-math'],
+ tasks: [{
+ module: 'mental-math', type: 'doubling-chain',
+ config: { startValue: 4, steps: 1 },
+ questions: [{ prompt: '4 x 2', answered: 8, responseMs: 500 }],
+ totalMs: 1234,
+ }],
+ tags: { mood: 'focused' },
+ });
+
+ const sessionWrite = atomicWrite.mock.calls.find(([path]) => String(path).includes('post-sessions'));
+ expect(sessionWrite).toBeTruthy();
+ const persisted = sessionWrite[1].sessions[0];
+ expect(persisted.durationMs).toBe(1234);
+ expect(persisted.tags).toEqual({ mood: 'focused' });
+ expect(persisted.id).toBeTruthy();
+ expect(persisted.date).toBeTruthy();
+ });
+});
diff --git a/server/services/meatspacePostLlm.test.js b/server/services/meatspacePostLlm.test.js
index dd8719b680..9fb62f5559 100644
--- a/server/services/meatspacePostLlm.test.js
+++ b/server/services/meatspacePostLlm.test.js
@@ -29,6 +29,15 @@ import {
generateVerbalFluency,
generateWitComeback,
generatePunWordplay,
+ generateCompoundChain,
+ generateBridgeWord,
+ generateDoubleMeaning,
+ generateIdiomTwist,
+ generateWhatIf,
+ generateAlternativeUses,
+ generateStoryPrompt,
+ generateInventionPitch,
+ generateReframe,
scoreLlmDrill
} from './meatspacePostLlm.js';
@@ -222,6 +231,265 @@ describe('generatePunWordplay', () => {
});
});
+// =============================================================================
+// COMPOUND CHAIN
+// =============================================================================
+
+describe('generateCompoundChain', () => {
+ it('returns compound-chain drill with challenges', async () => {
+ mockApiProvider({ challenges: [
+ { rootWord: 'paper', position: 'prefix', examples: ['paperback', 'paperweight'], minExpected: 8 }
+ ]});
+
+ const result = await generateCompoundChain({ count: 1 });
+ expect(result.type).toBe('compound-chain');
+ expect(result.config.count).toBe(1);
+ expect(result.challenges).toHaveLength(1);
+ expect(result.challenges[0].rootWord).toBe('paper');
+ expect(result.challenges[0].position).toBe('prefix');
+ expect(result.challenges[0].examples).toEqual(['paperback', 'paperweight']);
+ expect(result.challenges[0].minExpected).toBe(8);
+ });
+
+ it('defaults count to 5', async () => {
+ mockApiProvider({ challenges: Array.from({ length: 5 }, () => ({ rootWord: 'fire', position: 'both', examples: [], minExpected: 8 })) });
+ const result = await generateCompoundChain({});
+ expect(result.config.count).toBe(5);
+ });
+
+ it('defaults position, examples, and minExpected when absent', async () => {
+ mockApiProvider({ challenges: [{ rootWord: 'light' }] });
+ const result = await generateCompoundChain({ count: 1 });
+ expect(result.challenges[0].position).toBe('both');
+ expect(result.challenges[0].examples).toEqual([]);
+ expect(result.challenges[0].minExpected).toBe(8);
+ });
+});
+
+// =============================================================================
+// BRIDGE WORD
+// =============================================================================
+
+describe('generateBridgeWord', () => {
+ it('returns bridge-word drill with puzzles', async () => {
+ mockApiProvider({ puzzles: [
+ { clues: ['news___', '___back'], answer: 'paper', difficulty: 'easy', hint: 'You write on it' }
+ ]});
+
+ const result = await generateBridgeWord({ count: 1 });
+ expect(result.type).toBe('bridge-word');
+ expect(result.config.count).toBe(1);
+ expect(result.puzzles).toHaveLength(1);
+ expect(result.puzzles[0].clues).toEqual(['news___', '___back']);
+ expect(result.puzzles[0].answer).toBe('paper');
+ expect(result.puzzles[0].difficulty).toBe('easy');
+ expect(result.puzzles[0].hint).toBe('You write on it');
+ });
+
+ it('defaults count to 5', async () => {
+ mockApiProvider({ puzzles: Array.from({ length: 5 }, () => ({ clues: [], answer: 'x' })) });
+ const result = await generateBridgeWord({});
+ expect(result.config.count).toBe(5);
+ });
+
+ it('defaults clues, difficulty, and hint when absent', async () => {
+ mockApiProvider({ puzzles: [{ answer: 'paper' }] });
+ const result = await generateBridgeWord({ count: 1 });
+ expect(result.puzzles[0].clues).toEqual([]);
+ expect(result.puzzles[0].difficulty).toBe('medium');
+ expect(result.puzzles[0].hint).toBe('');
+ });
+});
+
+// =============================================================================
+// DOUBLE MEANING
+// =============================================================================
+
+describe('generateDoubleMeaning', () => {
+ it('returns double-meaning drill with challenges', async () => {
+ mockApiProvider({ challenges: [
+ { word: 'bark', meanings: ['tree covering', 'dog sound'], example: 'The bark of the dog echoed off the bark of the tree.', difficulty: 'easy' }
+ ]});
+
+ const result = await generateDoubleMeaning({ count: 1 });
+ expect(result.type).toBe('double-meaning');
+ expect(result.config.count).toBe(1);
+ expect(result.challenges).toHaveLength(1);
+ expect(result.challenges[0].word).toBe('bark');
+ expect(result.challenges[0].meanings).toEqual(['tree covering', 'dog sound']);
+ expect(result.challenges[0].difficulty).toBe('easy');
+ });
+
+ it('defaults count to 5', async () => {
+ mockApiProvider({ challenges: Array.from({ length: 5 }, () => ({ word: 'x', meanings: [] })) });
+ const result = await generateDoubleMeaning({});
+ expect(result.config.count).toBe(5);
+ });
+
+ it('defaults example, difficulty, and meanings when absent', async () => {
+ mockApiProvider({ challenges: [{ word: 'scale' }] });
+ const result = await generateDoubleMeaning({ count: 1 });
+ expect(result.challenges[0].meanings).toEqual([]);
+ expect(result.challenges[0].example).toBe('');
+ expect(result.challenges[0].difficulty).toBe('medium');
+ });
+});
+
+// =============================================================================
+// IDIOM TWIST
+// =============================================================================
+
+describe('generateIdiomTwist', () => {
+ it('returns idiom-twist drill with challenges', async () => {
+ mockApiProvider({ challenges: [
+ { idiom: "Don't put all your eggs in one basket", domain: 'programming', example: "Don't push all your commits to one branch", difficulty: 'easy' }
+ ]});
+
+ const result = await generateIdiomTwist({ count: 1 });
+ expect(result.type).toBe('idiom-twist');
+ expect(result.config.count).toBe(1);
+ expect(result.challenges).toHaveLength(1);
+ expect(result.challenges[0].idiom).toBe("Don't put all your eggs in one basket");
+ expect(result.challenges[0].domain).toBe('programming');
+ expect(result.challenges[0].difficulty).toBe('easy');
+ });
+
+ it('defaults count to 5', async () => {
+ mockApiProvider({ challenges: Array.from({ length: 5 }, () => ({ idiom: 'x', domain: 'y' })) });
+ const result = await generateIdiomTwist({});
+ expect(result.config.count).toBe(5);
+ });
+
+ it('defaults example and difficulty when absent', async () => {
+ mockApiProvider({ challenges: [{ idiom: 'x', domain: 'y' }] });
+ const result = await generateIdiomTwist({ count: 1 });
+ expect(result.challenges[0].example).toBe('');
+ expect(result.challenges[0].difficulty).toBe('medium');
+ });
+});
+
+// =============================================================================
+// WHAT IF
+// =============================================================================
+
+describe('generateWhatIf', () => {
+ it('returns what-if drill with scenarios', async () => {
+ mockApiProvider({ scenarios: [
+ { prompt: 'What if gravity reversed for 10 minutes every Tuesday?', category: 'physics' }
+ ]});
+
+ const result = await generateWhatIf({ count: 1 });
+ expect(result.type).toBe('what-if');
+ expect(result.config.count).toBe(1);
+ expect(result.scenarios).toHaveLength(1);
+ expect(result.scenarios[0].category).toBe('physics');
+ });
+
+ it('defaults count to 3', async () => {
+ mockApiProvider({ scenarios: Array.from({ length: 3 }, () => ({ prompt: 'x', category: 'y' })) });
+ const result = await generateWhatIf({});
+ expect(result.config.count).toBe(3);
+ });
+});
+
+// =============================================================================
+// ALTERNATIVE USES
+// =============================================================================
+
+describe('generateAlternativeUses', () => {
+ it('returns alternative-uses drill with objects', async () => {
+ mockApiProvider({ objects: [
+ { object: 'brick', commonUse: 'building material', minExpected: 8 }
+ ]});
+
+ const result = await generateAlternativeUses({ count: 1 });
+ expect(result.type).toBe('alternative-uses');
+ expect(result.config.count).toBe(1);
+ expect(result.objects).toHaveLength(1);
+ expect(result.objects[0].object).toBe('brick');
+ expect(result.objects[0].minExpected).toBe(8);
+ });
+
+ it('defaults count to 3', async () => {
+ mockApiProvider({ objects: Array.from({ length: 3 }, () => ({ object: 'x', commonUse: 'y', minExpected: 5 })) });
+ const result = await generateAlternativeUses({});
+ expect(result.config.count).toBe(3);
+ });
+});
+
+// =============================================================================
+// STORY PROMPT
+// =============================================================================
+
+describe('generateStoryPrompt', () => {
+ it('returns story-prompt drill with prompts', async () => {
+ mockApiProvider({ prompts: [
+ { words: ['lighthouse', 'saxophone', 'marmalade'] }
+ ]});
+
+ const result = await generateStoryPrompt({ count: 1 });
+ expect(result.type).toBe('story-prompt');
+ expect(result.config.count).toBe(1);
+ expect(result.prompts).toHaveLength(1);
+ expect(result.prompts[0].words).toEqual(['lighthouse', 'saxophone', 'marmalade']);
+ });
+
+ it('defaults count to 3', async () => {
+ mockApiProvider({ prompts: Array.from({ length: 3 }, () => ({ words: ['a', 'b', 'c'] })) });
+ const result = await generateStoryPrompt({});
+ expect(result.config.count).toBe(3);
+ });
+});
+
+// =============================================================================
+// INVENTION PITCH
+// =============================================================================
+
+describe('generateInventionPitch', () => {
+ it('returns invention-pitch drill with problems', async () => {
+ mockApiProvider({ problems: [
+ { problem: 'You always forget where you put your keys', category: 'everyday', difficulty: 'easy' }
+ ]});
+
+ const result = await generateInventionPitch({ count: 1 });
+ expect(result.type).toBe('invention-pitch');
+ expect(result.config.count).toBe(1);
+ expect(result.problems).toHaveLength(1);
+ expect(result.problems[0].category).toBe('everyday');
+ expect(result.problems[0].difficulty).toBe('easy');
+ });
+
+ it('defaults count to 3', async () => {
+ mockApiProvider({ problems: Array.from({ length: 3 }, () => ({ problem: 'x', category: 'y', difficulty: 'medium' })) });
+ const result = await generateInventionPitch({});
+ expect(result.config.count).toBe(3);
+ });
+});
+
+// =============================================================================
+// REFRAME
+// =============================================================================
+
+describe('generateReframe', () => {
+ it('returns reframe drill with situations', async () => {
+ mockApiProvider({ situations: [
+ { situation: 'Your flight was delayed by 4 hours', severity: 'medium' }
+ ]});
+
+ const result = await generateReframe({ count: 1 });
+ expect(result.type).toBe('reframe');
+ expect(result.config.count).toBe(1);
+ expect(result.situations).toHaveLength(1);
+ expect(result.situations[0].severity).toBe('medium');
+ });
+
+ it('defaults count to 3', async () => {
+ mockApiProvider({ situations: Array.from({ length: 3 }, () => ({ situation: 'x', severity: 'low' })) });
+ const result = await generateReframe({});
+ expect(result.config.count).toBe(3);
+ });
+});
+
// =============================================================================
// generateLlmDrill ROUTER
// =============================================================================
@@ -247,6 +515,42 @@ describe('generateLlmDrill', () => {
mockApiProvider({ challenges: [{ type: 'pun-topic', prompt: 'x', topic: 'y', example: 'z' }] });
const pw = await generateLlmDrill('pun-wordplay', { count: 1 });
expect(pw.type).toBe('pun-wordplay');
+
+ mockApiProvider({ challenges: [{ rootWord: 'fire', position: 'both', examples: [], minExpected: 8 }] });
+ const cc = await generateLlmDrill('compound-chain', { count: 1 });
+ expect(cc.type).toBe('compound-chain');
+
+ mockApiProvider({ puzzles: [{ answer: 'paper' }] });
+ const bw = await generateLlmDrill('bridge-word', { count: 1 });
+ expect(bw.type).toBe('bridge-word');
+
+ mockApiProvider({ challenges: [{ word: 'bark', meanings: [] }] });
+ const dm = await generateLlmDrill('double-meaning', { count: 1 });
+ expect(dm.type).toBe('double-meaning');
+
+ mockApiProvider({ challenges: [{ idiom: 'x', domain: 'y' }] });
+ const twist = await generateLlmDrill('idiom-twist', { count: 1 });
+ expect(twist.type).toBe('idiom-twist');
+
+ mockApiProvider({ scenarios: [{ prompt: 'x', category: 'y' }] });
+ const wi = await generateLlmDrill('what-if', { count: 1 });
+ expect(wi.type).toBe('what-if');
+
+ mockApiProvider({ objects: [{ object: 'x', commonUse: 'y', minExpected: 5 }] });
+ const au = await generateLlmDrill('alternative-uses', { count: 1 });
+ expect(au.type).toBe('alternative-uses');
+
+ mockApiProvider({ prompts: [{ words: ['a', 'b', 'c'] }] });
+ const sp = await generateLlmDrill('story-prompt', { count: 1 });
+ expect(sp.type).toBe('story-prompt');
+
+ mockApiProvider({ problems: [{ problem: 'x', category: 'y', difficulty: 'easy' }] });
+ const ip = await generateLlmDrill('invention-pitch', { count: 1 });
+ expect(ip.type).toBe('invention-pitch');
+
+ mockApiProvider({ situations: [{ situation: 'x', severity: 'low' }] });
+ const rf = await generateLlmDrill('reframe', { count: 1 });
+ expect(rf.type).toBe('reframe');
});
it('returns null for unknown type', async () => {
@@ -437,6 +741,93 @@ describe('scoreLlmDrill', () => {
});
});
+// =============================================================================
+// LOCAL SCORING — BRIDGE WORD
+// =============================================================================
+
+describe('scoreLlmDrill bridge-word (local scoring)', () => {
+ it('scores 100 for an exact match (case/whitespace insensitive)', async () => {
+ const result = await scoreLlmDrill(
+ 'bridge-word',
+ { puzzles: [{ clues: ['news___', '___back'], answer: 'paper' }] },
+ [{ response: ' Paper ', responseMs: 5000 }],
+ 60000
+ );
+
+ expect(result.evaluation.scores[0].score).toBe(100);
+ expect(result.evaluation.scores[0].feedback).toBe('Correct!');
+ expect(result.evaluation.overallScore).toBe(100);
+ });
+
+ it('scores 0 for a wrong answer with "the answer was" feedback', async () => {
+ const result = await scoreLlmDrill(
+ 'bridge-word',
+ { puzzles: [{ clues: ['news___', '___back'], answer: 'paper' }] },
+ [{ response: 'wood', responseMs: 5000 }],
+ 60000
+ );
+
+ expect(result.evaluation.scores[0].score).toBe(0);
+ expect(result.evaluation.scores[0].feedback).toBe('The answer was "paper"');
+ });
+
+ it('falls back to "no answer available" when the puzzle does not resolve', async () => {
+ const result = await scoreLlmDrill(
+ 'bridge-word',
+ { puzzles: [] },
+ [{ response: 'paper', responseMs: 5000 }],
+ 60000
+ );
+
+ expect(result.evaluation.scores[0].score).toBe(0);
+ expect(result.evaluation.scores[0].feedback).toBe('No answer available');
+ });
+});
+
+// =============================================================================
+// LLM SCORING — DOUBLE MEANING / IDIOM TWIST
+// =============================================================================
+
+describe('scoreLlmDrill double-meaning and idiom-twist (LLM scoring)', () => {
+ it('scores double-meaning with evaluation and per-response feedback', async () => {
+ mockApiProvider({
+ overallScore: 85,
+ scores: [{ score: 90, feedback: 'Both meanings used cleverly' }],
+ summary: 'Great wordplay'
+ });
+
+ const result = await scoreLlmDrill(
+ 'double-meaning',
+ { challenges: [{ word: 'bark', meanings: ['tree covering', 'dog sound'] }] },
+ [{ response: "The dog's bark echoed off the bark of the tree.", responseMs: 8000 }],
+ 60000
+ );
+
+ expect(result.evaluation.overallScore).toBe(85);
+ expect(result.questions[0].llmScore).toBe(90);
+ expect(result.questions[0].llmFeedback).toBe('Both meanings used cleverly');
+ });
+
+ it('scores idiom-twist with evaluation and per-response feedback', async () => {
+ mockApiProvider({
+ overallScore: 70,
+ scores: [{ score: 75, feedback: 'Good structural parallel' }],
+ summary: 'Solid twist'
+ });
+
+ const result = await scoreLlmDrill(
+ 'idiom-twist',
+ { challenges: [{ idiom: "Don't put all your eggs in one basket", domain: 'programming' }] },
+ [{ response: "Don't push all your commits to one branch", responseMs: 8000 }],
+ 60000
+ );
+
+ expect(result.evaluation.overallScore).toBe(70);
+ expect(result.questions[0].llmScore).toBe(75);
+ expect(result.questions[0].llmFeedback).toBe('Good structural parallel');
+ });
+});
+
// =============================================================================
// PROVIDER SELECTION
// =============================================================================
diff --git a/server/services/meatspacePostMemory.test.js b/server/services/meatspacePostMemory.test.js
index 05ae014219..ff380edfb2 100644
--- a/server/services/meatspacePostMemory.test.js
+++ b/server/services/meatspacePostMemory.test.js
@@ -20,6 +20,7 @@ import {
advanceScheduleFromSession,
mergeMasteryFromSession,
getMastery,
+ getChunkMasteryOrder,
generateMemoryDrill,
getDueMemoryItems,
advanceSchedule,
@@ -152,6 +153,134 @@ describe('deleteMemoryItem', () => {
});
});
+// =============================================================================
+// UPDATE MEMORY ITEM — built-in "mastery only" restriction (gap #8, issue #2102)
+// =============================================================================
+
+describe('updateMemoryItem', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('returns null for an unknown id', async () => {
+ readJSONFile.mockResolvedValue({ items: [] });
+ const result = await updateMemoryItem('does-not-exist', { title: 'New Title' });
+ expect(result).toBeNull();
+ expect(atomicWrite).not.toHaveBeenCalled();
+ });
+
+ it('built-in items: applies a mastery update', async () => {
+ readJSONFile.mockResolvedValue({ items: [{ ...ELEMENTS_SONG }] });
+ const newMastery = { overallPct: 42, chunks: {}, elements: {} };
+ const result = await updateMemoryItem('elements-song', { mastery: newMastery });
+ expect(result.mastery).toEqual(newMastery);
+ expect(atomicWrite).toHaveBeenCalled();
+ });
+
+ it('built-in items: applies a schedule update', async () => {
+ readJSONFile.mockResolvedValue({ items: [{ ...ELEMENTS_SONG }] });
+ const newSchedule = { ease: 2.8, intervalDays: 3, nextReview: '2026-07-10T00:00:00.000Z', lastReviewed: '2026-07-07T00:00:00.000Z' };
+ const result = await updateMemoryItem('elements-song', { schedule: newSchedule });
+ expect(result.schedule).toEqual(newSchedule);
+ });
+
+ it('built-in items: ignores title/lines/chunks updates (mastery/schedule only)', async () => {
+ readJSONFile.mockResolvedValue({ items: [{ ...ELEMENTS_SONG }] });
+ const originalTitle = ELEMENTS_SONG.title;
+ const originalLineCount = ELEMENTS_SONG.content.lines.length;
+ const result = await updateMemoryItem('elements-song', {
+ title: 'Hacked Title',
+ lines: ['only one line now'],
+ });
+ // Neither mastery nor schedule was in the patch, so the built-in branch's
+ // "if (updates.mastery || updates.schedule)" guard is never entered — the
+ // item is returned completely untouched (no write at all).
+ expect(result.title).toBe(originalTitle);
+ expect(result.content.lines.length).toBe(originalLineCount);
+ expect(atomicWrite).not.toHaveBeenCalled();
+ });
+
+ it('custom items: applies title/lines/chunks updates freely', async () => {
+ readJSONFile.mockResolvedValue({
+ items: [{
+ id: 'custom-1', title: 'Old Title', builtin: false, type: 'text',
+ content: { lines: [{ text: 'old line' }], chunks: [] },
+ mastery: { overallPct: 0, chunks: {}, elements: {} },
+ }],
+ });
+ const result = await updateMemoryItem('custom-1', {
+ title: 'New Title',
+ lines: ['new line one', 'new line two'],
+ });
+ expect(result.title).toBe('New Title');
+ expect(result.content.lines).toEqual([{ text: 'new line one' }, { text: 'new line two' }]);
+ });
+});
+
+// =============================================================================
+// getChunkMasteryOrder — spaced-repetition practice ordering (gap #8, issue #2102)
+// =============================================================================
+
+describe('getChunkMasteryOrder', () => {
+ it('sorts chunks worst-mastery-first', () => {
+ const item = {
+ content: {
+ chunks: [
+ { id: 'verse-1', lineRange: [0, 2], label: 'Verse 1' },
+ { id: 'verse-2', lineRange: [3, 5], label: 'Verse 2' },
+ { id: 'verse-3', lineRange: [6, 8], label: 'Verse 3' },
+ ],
+ },
+ mastery: {
+ chunks: {
+ 'verse-1': { correct: 9, attempts: 10, lastPracticed: '2026-07-01T00:00:00.000Z' },
+ 'verse-2': { correct: 1, attempts: 10, lastPracticed: '2026-07-02T00:00:00.000Z' },
+ // verse-3 has no recorded stats
+ },
+ },
+ };
+ const order = getChunkMasteryOrder(item);
+ expect(order.map(c => c.id)).toEqual(['verse-3', 'verse-2', 'verse-1']);
+ expect(order.find(c => c.id === 'verse-1').accuracy).toBe(90);
+ expect(order.find(c => c.id === 'verse-2').accuracy).toBe(10);
+ expect(order.find(c => c.id === 'verse-3').accuracy).toBe(0);
+ expect(order.find(c => c.id === 'verse-3').attempts).toBe(0);
+ expect(order.find(c => c.id === 'verse-3').lastPracticed).toBeNull();
+ });
+
+ it('derives hint levels from accuracy thresholds (0/1/2/3)', () => {
+ const item = {
+ content: {
+ chunks: [
+ { id: 'a', lineRange: [0, 0], label: 'A' }, // 95% -> no hints (3)
+ { id: 'b', lineRange: [1, 1], label: 'B' }, // 75% -> minimal (2)
+ { id: 'c', lineRange: [2, 2], label: 'C' }, // 50% -> partial (1)
+ { id: 'd', lineRange: [3, 3], label: 'D' }, // 20% -> full hints (0)
+ ],
+ },
+ mastery: {
+ chunks: {
+ a: { correct: 19, attempts: 20 },
+ b: { correct: 3, attempts: 4 },
+ c: { correct: 1, attempts: 2 },
+ d: { correct: 1, attempts: 5 },
+ },
+ },
+ };
+ const order = getChunkMasteryOrder(item);
+ const byId = Object.fromEntries(order.map(c => [c.id, c]));
+ expect(byId.a.hintLevel).toBe(3);
+ expect(byId.b.hintLevel).toBe(2);
+ expect(byId.c.hintLevel).toBe(1);
+ expect(byId.d.hintLevel).toBe(0);
+ });
+
+ it('returns an empty array when the item has no chunks', () => {
+ expect(getChunkMasteryOrder({ content: {}, mastery: {} })).toEqual([]);
+ expect(getChunkMasteryOrder({})).toEqual([]);
+ });
+});
+
// =============================================================================
// DRILL GENERATION
// =============================================================================