Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: make POST memory recall retrieval-only (#4448)
[._.]/ Adam Eivy526ef8ff5b32
diff --git a/.changelog/next/fixed-issue-4448.md b/.changelog/next/fixed-issue-4448.mdnew file mode 100644index 0000000000..ba6bb80da5--- /dev/null+++ b/.changelog/next/fixed-issue-4448.md@@ -0,0 +1 @@+- POST memory practice now separates study exposure from retrieval mastery and scores every fill-in-the-blank answer.diff --git a/client/src/components/meatspace/post/DrillQuestionReview.jsx b/client/src/components/meatspace/post/DrillQuestionReview.jsxindex 98655f30e5..c96b7f79a1 100644--- a/client/src/components/meatspace/post/DrillQuestionReview.jsx+++ b/client/src/components/meatspace/post/DrillQuestionReview.jsx@@ -8,7 +8,10 @@ import { powersBreakdownFromPrompt } from '../../../lib/powersBreakdown.js';// narrower formatter for that reason.const fmtMs = (ms) => `${(Math.max(0, ms || 0) / 1000).toFixed(1)}s`;-const isUnanswered = (q) => q.answered === null || q.answered === undefined;+const isUnanswered = (q) => {+ if (Array.isArray(q.answered)) return !q.answered.some(answer => answer?.value != null && String(answer.value).trim() !== '');+ return q.answered === null || q.answered === undefined;+};function ResultIcon({ correct, unanswered }) {if (unanswered) return <MinusCircle size={13} className="text-gray-500 shrink-0" />;@@ -74,15 +77,13 @@ function formatGenericValue(type, value) {return String(value);}-// memory-fill-blank (schema-valid, generated by generateFillBlank, but not-// yet wired into the interactive POST session drill picker — see-// POST_UNSUPPORTED_DRILL_TYPES in constants.js) carries acceptable answers as-// `answers[]` objects (`{ index, word, element }`) instead of a scalar-// `expected`. Fall back to those so this generic view never just shows "—"-// for every row if that type is ever produced, without conflating this-// display-only fallback with the separate, pre-existing scoring gap for that-// type in usePostSession.js (out of scope here, not yet filed as an issue).+// memory-fill-blank carries one indexed response per generated blank. Use the+// response-local answer key in history so partial credit is visible even after+// the original generated question is no longer present.function expectedForDisplay(q) {+ if (Array.isArray(q.answered) && q.answered.length) {+ return q.answered.map(answer => answer?.expected || '—').join(' / ');+ }if (q.expected !== null && q.expected !== undefined && q.expected !== '') return q.expected;if (Array.isArray(q.answers) && q.answers.length) {return q.answers.map((a) => (a && typeof a === 'object' ? a.word : a)).filter(Boolean).join(' / ');@@ -90,6 +91,13 @@ function expectedForDisplay(q) {return q.expected;}+function answeredForDisplay(type, q) {+ if (type === 'memory-fill-blank' && Array.isArray(q.answered)) {+ return q.answered.map(answer => answer?.value || '—').join(' / ');+ }+ return formatGenericValue(type, q.answered);+}+function GenericReview({ questions, missed, type }) {return (<div>@@ -113,10 +121,19 @@ function GenericReview({ questions, missed, type }) {<td className="py-1 pr-2 font-mono">{unanswered? <span className="italic text-gray-500">skipped</span>- : formatGenericValue(type, q.answered)}+ : answeredForDisplay(type, q)}</td><td className="py-1 pr-2 font-mono text-port-success">{formatGenericValue(type, expectedForDisplay(q))}</td>- <td className="py-1 pr-2 text-center"><ResultIcon correct={q.correct} unanswered={unanswered} /></td>+ <td className="py-1 pr-2 text-center">+ <div className="inline-flex items-center gap-1">+ <ResultIcon correct={q.correct} unanswered={unanswered} />+ {type === 'memory-fill-blank' && Array.isArray(q.answered) && (+ <span className="text-[11px] text-gray-400">+ {q.answered.filter(answer => answer?.correct).length}/{q.answered.length}+ </span>+ )}+ </div>+ </td><td className="py-1 pl-2 text-right text-gray-400 font-mono">{fmtMs(q.responseMs)}</td></tr>);diff --git a/client/src/components/meatspace/post/ElementsSong.jsx b/client/src/components/meatspace/post/ElementsSong.jsxindex a3c43ce1d5..62c5ea8464 100644--- a/client/src/components/meatspace/post/ElementsSong.jsx+++ b/client/src/components/meatspace/post/ElementsSong.jsx@@ -617,7 +617,7 @@ function LearnMode({ item, onBack, onComplete }) {function save(continueDaily) {return submitMemoryPractice(item.id, {mode: 'learn', chunkId: null,- results: [{ correct: true }],+ results: [],totalMs: 0,}).then(r => onComplete(r?.mastery, continueDaily));}@@ -733,7 +733,9 @@ function ElementStudyMode({ item, mastery, onBack, onComplete }) {function save(continueDaily) {return submitMemoryPractice(item.id, {mode: 'element-study', chunkId: null,- results: results.map(r => ({ correct: r.correct, element: r.element })),+ // Flash-card exposure is not scored retrieval. Keep the local self-rating+ // for this screen, but never submit it as mastery evidence.+ results: [],totalMs: Date.now() - startTime,}).then(r => onComplete(r?.mastery, continueDaily));}diff --git a/client/src/components/meatspace/post/ElementsSong.test.jsx b/client/src/components/meatspace/post/ElementsSong.test.jsxindex 264a151f33..7d0f3d8aed 100644--- a/client/src/components/meatspace/post/ElementsSong.test.jsx+++ b/client/src/components/meatspace/post/ElementsSong.test.jsx@@ -4,10 +4,10 @@ import { render, screen, fireEvent, act } from '@testing-library/react';import ElementsSong, { elementMasteryProgress, recommendedElementsMode } from './ElementsSong';// The Flash Cards study mode (issue #2480) is a flip-to-reveal study surface —-// distinct from the Element Flash recall test — that must still advance element-// mastery through the shared submitMemoryPractice path. These tests pin that-// contract: the mode is offered, a card flips + self-rates, and completing the-// deck submits `mode: 'element-study'` with element-tagged results.+// distinct from the Element Flash recall test — self-ratings are exposure, not+// retrieval evidence. These tests pin that the mode is offered, a card flips ++// self-rates locally, and completing the deck submits an activity-only+// `mode: 'element-study'` event.const submitMemoryPractice = vi.fn(() => Promise.resolve({ mastery: { overallPct: 10, chunks: {}, elements: {} } }));const attestMemoryMastery = vi.fn(() => Promise.resolve({@@ -71,7 +71,7 @@ describe('ElementsSong — Flash Cards study mode', () => {expect(screen.getByText('Element Flash')).toBeInTheDocument();});- it('flips a card to reveal the pairing, then self-rates through the deck and submits element-study mastery', async () => {+ it('flips a card to reveal the pairing, then records the deck as exposure', async () => {render(<RoutedElementsSong item={item} onBack={() => {}} />);await settle();@@ -97,11 +97,7 @@ describe('ElementsSong — Flash Cards study mode', () => {const [id, payload] = submitMemoryPractice.mock.calls[0];expect(id).toBe('elements-song');expect(payload.mode).toBe('element-study');- expect(payload.results).toHaveLength(2);- // Every result is element-tagged (drives per-element mastery server-side) and- // exactly one was marked known.- expect(payload.results.every((r) => r.element === 'H' || r.element === 'He')).toBe(true);- expect(payload.results.filter((r) => r.correct)).toHaveLength(1);+ expect(payload.results).toEqual([]);});it('saves the deck before continuing the daily routine', async () => {diff --git a/client/src/components/meatspace/post/MemoryPractice.jsx b/client/src/components/meatspace/post/MemoryPractice.jsxindex 1adeaf2665..de043aea70 100644--- a/client/src/components/meatspace/post/MemoryPractice.jsx+++ b/client/src/components/meatspace/post/MemoryPractice.jsx@@ -276,6 +276,7 @@ function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, on}if (done) {+ const exposureOnly = mode === 'learn';const correct = results.filter(r => r.correct).length;const pct = results.length > 0 ? Math.round((correct / results.length) * 100) : 0;const scoreColor = pct >= 80 ? 'text-port-success' : pct >= 50 ? 'text-port-warning' : 'text-port-error';@@ -290,15 +291,24 @@ function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, on</div><div className="bg-port-card border border-port-border rounded-lg p-6 text-center">- <div className={`text-5xl font-bold font-mono ${scoreColor} mb-2`}>{pct}%</div>- <div className="text-gray-400 text-sm">{correct} of {results.length} correct</div>+ {exposureOnly ? (+ <>+ <div className="text-2xl font-semibold text-port-accent mb-2">Study complete</div>+ <div className="text-gray-400 text-sm">Exposure recorded; no retrieval score or mastery update.</div>+ </>+ ) : (+ <>+ <div className={`text-5xl font-bold font-mono ${scoreColor} mb-2`}>{pct}%</div>+ <div className="text-gray-400 text-sm">{correct} of {results.length} correct</div>+ </>+ )}<div className="text-gray-500 text-xs mt-1">{Math.round((Date.now() - startTime) / 1000)}s elapsed</div></div>{/* Show wrong answers */}- {results.filter(r => !r.correct).length > 0 && (+ {!exposureOnly && results.filter(r => !r.correct).length > 0 && (<div className="bg-port-card border border-port-border rounded-lg p-4"><h3 className="text-sm font-medium text-gray-400 mb-3">Review mistakes</h3><div className="space-y-2">@@ -516,7 +526,7 @@ function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, on</button>) : (<button- onClick={() => { setDone(true); setResults([{ correct: true, expected: 'learn mode', answered: 'learn mode' }]); }}+ onClick={() => { setDone(true); setResults([]); }}className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors"><Check size={16} />@@ -810,6 +820,15 @@ function MemoryPracticeRunner({ item, mode, onSelectMode, onExitMode, onBack, on}async function savePractice(practiceMode, practiceResults) {+ if (practiceMode === 'learn') {+ await submitMemoryPractice(item.id, {+ mode: practiceMode,+ chunkId: null,+ results: [],+ totalMs: Date.now() - startTime,+ });+ return;+ }const chunkId = findChunkForLine(item, currentIdx);await submitMemoryPractice(item.id, {mode: practiceMode,diff --git a/client/src/components/meatspace/post/MemoryPractice.test.jsx b/client/src/components/meatspace/post/MemoryPractice.test.jsxindex 8607ca1171..3477d8022b 100644--- a/client/src/components/meatspace/post/MemoryPractice.test.jsx+++ b/client/src/components/meatspace/post/MemoryPractice.test.jsx@@ -264,6 +264,11 @@ describe('MemoryPractice daily routine actions', () => {fireEvent.click(screen.getByText("Continue Today's Routine"));await waitFor(() => expect(submitMemoryPractice).toHaveBeenCalledTimes(1));+ expect(submitMemoryPractice.mock.calls[0][1]).toMatchObject({+ mode: 'learn',+ chunkId: null,+ results: [],+ });expect(onContinue).not.toHaveBeenCalled();await act(async () => resolveSave({ mastery: {} }));diff --git a/client/src/components/meatspace/post/PostDrillRunner.jsx b/client/src/components/meatspace/post/PostDrillRunner.jsxindex 602be6e350..cc7fd7ced8 100644--- a/client/src/components/meatspace/post/PostDrillRunner.jsx+++ b/client/src/components/meatspace/post/PostDrillRunner.jsx@@ -33,6 +33,7 @@ export default function PostDrillRunner({ session }) {} = session;const [inputValue, setInputValue] = useState('');+ const [blankValues, setBlankValues] = useState({});const [timeLeft, setTimeLeft] = useState(0);const inputRef = useRef(null);const timerRef = useRef(null);@@ -40,6 +41,10 @@ export default function PostDrillRunner({ session }) {const timeLimitMs = (currentDrill?.timeLimitSec || 120) * 1000;const totalQuestions = currentDrill?.questions?.length || 0;+ const question = currentDrill?.questions?.[currentQuestionIndex];+ const isFillBlankQuestion = currentDrill?.type === 'memory-fill-blank'+ && Array.isArray(question?.answers)+ && question.answers.length > 0;// Keep ref current to avoid stale closure in timeruseEffect(() => {@@ -75,14 +80,24 @@ export default function PostDrillRunner({ session }) {// Auto-focus input on question changeuseEffect(() => {setInputValue('');+ setBlankValues({});inputRef.current?.focus();}, [currentQuestionIndex, currentDrillIndex]);const handleSubmit = useCallback((e) => {e.preventDefault();+ if (isFillBlankQuestion) {+ const values = question.answers.map(answer => ({+ index: answer.index,+ value: blankValues[answer.index] || null,+ }));+ if (!values.some(entry => entry.value != null)) return;+ submitAnswer(values);+ return;+ }if (inputValue.trim() === '') return;submitAnswer(inputValue.trim());- }, [inputValue, submitAnswer]);+ }, [blankValues, inputValue, isFillBlankQuestion, question, submitAnswer]);if (state === 'loading') {return (@@ -94,7 +109,6 @@ export default function PostDrillRunner({ session }) {if (state !== 'drilling' || !currentDrill) return null;- const question = currentDrill.questions?.[currentQuestionIndex];// MEMORY_DRILL_TYPES now includes 'memory-fill-blank' (issue #2099/#2116),// so the explicit extra check this used to need is gone.const isTextDrill = MEMORY_DRILL_TYPES.includes(currentDrill.type);@@ -108,6 +122,8 @@ export default function PostDrillRunner({ session }) {// Training mode: show feedback overlayif (isTraining && lastAnswer) {+ const structuredAnswers = Array.isArray(lastAnswer.answered) ? lastAnswer.answered : null;+ const structuredCorrect = structuredAnswers?.filter(answer => answer.correct).length;return (<div className="max-w-lg mx-auto space-y-6"><div className="flex items-center justify-between text-sm text-gray-400">@@ -120,19 +136,40 @@ export default function PostDrillRunner({ session }) {{lastAnswer.correct ? (<div className="flex flex-col items-center gap-2"><CheckCircle size={48} className="text-port-success" />- <div className="text-3xl font-mono font-bold text-port-success">{lastAnswer.answered}</div>- <div className="text-sm text-gray-400">Correct</div>+ {structuredAnswers ? (+ <div className="space-y-1 text-left font-mono text-port-success">+ {structuredAnswers.map(answer => <div key={answer.index}>{answer.value}</div>)}+ </div>+ ) : <div className="text-3xl font-mono font-bold text-port-success">{lastAnswer.answered}</div>}+ <div className="text-sm text-gray-400">+ {structuredAnswers ? `${structuredCorrect} of ${structuredAnswers.length} blanks correct` : 'Correct'}+ </div></div>) : (<div className="flex flex-col items-center gap-3"><XCircle size={48} className="text-port-error" />- {lastAnswer.answered != null ? (+ {structuredAnswers ? (+ <div className="space-y-1 text-left font-mono text-port-error">+ {structuredAnswers.map(answer => (+ <div key={answer.index}>+ <span className={answer.correct ? 'text-port-success' : 'line-through'}>{answer.value || '—'}</span>+ {!answer.correct && <span className="text-port-success ml-2">→ {answer.expected}</span>}+ </div>+ ))}+ </div>+ ) : lastAnswer.answered != null ? (<div className="text-2xl font-mono text-port-error line-through">{lastAnswer.answered}</div>) : (<div className="text-sm text-gray-500">Skipped</div>)}- <div className="text-sm text-gray-400">Expected</div>- <div className="text-3xl font-mono font-bold text-port-success">{lastAnswer.expected}</div>+ {structuredAnswers ? (+ <div className="text-sm text-gray-400">{structuredCorrect} of {structuredAnswers.length} blanks correct</div>+ ) : (+ <>+ <div className="text-sm text-gray-400">Expected</div>+ <div className="text-3xl font-mono font-bold text-port-success">{lastAnswer.expected}</div>+ </>+ )}<PowersLesson prompt={lastAnswer.prompt} />{/* Hint: break down the calculation */}{lastAnswer.prompt && powersBreakdownFromPrompt(lastAnswer.prompt)?.fallback !== false && (@@ -207,21 +244,47 @@ export default function PostDrillRunner({ session }) {</div>{/* Input */}- <form onSubmit={handleSubmit} className="flex gap-3">- <input- ref={inputRef}- type={isTextDrill ? 'text' : 'number'}- inputMode={isTextDrill ? 'text' : 'numeric'}- value={inputValue}- onChange={e => setInputValue(e.target.value)}- placeholder="Answer"- aria-label="Your answer"- autoFocus- className="flex-1 bg-port-bg border border-port-border rounded-lg px-4 py-3 text-xl font-mono text-white text-center placeholder-gray-600 focus:border-port-accent focus:outline-none"- />+ <form onSubmit={handleSubmit} className="space-y-3">+ {isFillBlankQuestion ? (+ <div className="space-y-3">+ <div className="text-sm text-gray-400">Fill every blank. Partial recall earns partial credit.</div>+ {question.answers.map((answer, index) => {+ const inputId = `post-blank-${currentDrillIndex}-${currentQuestionIndex}-${answer.index}`;+ return (+ <div key={answer.index}>+ <label htmlFor={inputId} className="block text-xs text-gray-500 mb-1">Blank {index + 1}</label>+ <input+ id={inputId}+ ref={index === 0 ? inputRef : undefined}+ type="text"+ value={blankValues[answer.index] || ''}+ onChange={e => setBlankValues(prev => ({ ...prev, [answer.index]: e.target.value }))}+ placeholder={`Answer for blank ${index + 1}`}+ autoFocus={index === 0}+ className="w-full bg-port-bg border border-port-border rounded-lg px-4 py-3 text-xl font-mono text-white text-center placeholder-gray-600 focus:border-port-accent focus:outline-none"+ />+ </div>+ );+ })}+ </div>+ ) : (+ <input+ ref={inputRef}+ type={isTextDrill ? 'text' : 'number'}+ inputMode={isTextDrill ? 'text' : 'numeric'}+ value={inputValue}+ onChange={e => setInputValue(e.target.value)}+ placeholder="Answer"+ aria-label="Your answer"+ autoFocus+ className="w-full bg-port-bg border border-port-border rounded-lg px-4 py-3 text-xl font-mono text-white text-center placeholder-gray-600 focus:border-port-accent focus:outline-none"+ />+ )}<buttontype="submit"- disabled={inputValue.trim() === ''}+ disabled={isFillBlankQuestion+ ? !Object.values(blankValues).some(value => value.trim() !== '')+ : inputValue.trim() === ''}className={`px-6 py-3 ${isTraining ? 'bg-port-accent-2 hover:bg-port-accent-2/80 text-port-on-accent-2' : 'bg-port-accent hover:bg-port-accent/80 text-white'} disabled:opacity-50 font-medium rounded-lg transition-colors`}>Enterdiff --git a/client/src/components/meatspace/post/PostDrillRunner.test.jsx b/client/src/components/meatspace/post/PostDrillRunner.test.jsxindex 8dd6c1b0e7..829197d2ed 100644--- a/client/src/components/meatspace/post/PostDrillRunner.test.jsx+++ b/client/src/components/meatspace/post/PostDrillRunner.test.jsx@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest';-import { render, screen } from '@testing-library/react';+import { fireEvent, render, screen } from '@testing-library/react';import PostDrillRunner from './PostDrillRunner';describe('PostDrillRunner Powers training feedback', () => {@@ -22,3 +22,42 @@ describe('PostDrillRunner Powers training feedback', () => {expect(screen.getByText('× 2 → 2^13 = 8,192')).toBeInTheDocument();});});++describe('PostDrillRunner multi-blank recall', () => {+ it('renders one labeled input per blank and submits indexed values', () => {+ const submitAnswer = vi.fn();+ render(<PostDrillRunner session={{+ currentDrill: {+ type: 'memory-fill-blank',+ questions: [{+ prompt: 'The ____ ____',+ answers: [+ { index: 1, word: 'quick' },+ { index: 2, word: 'fox' },+ ],+ }],+ timeLimitSec: 60,+ },+ currentQuestionIndex: 0,+ currentDrillIndex: 0,+ drillCount: 1,+ state: 'drilling',+ isTraining: false,+ lastAnswer: null,+ submitAnswer,+ skipQuestion: vi.fn(),+ acknowledgeAnswer: vi.fn(),+ timeExpired: vi.fn(),+ }} />);++ expect(screen.getByLabelText('Blank 1')).toBeInTheDocument();+ expect(screen.getByLabelText('Blank 2')).toBeInTheDocument();+ fireEvent.change(screen.getByLabelText('Blank 2'), { target: { value: 'fox' } });+ fireEvent.click(screen.getByRole('button', { name: 'Enter' }));++ expect(submitAnswer).toHaveBeenCalledWith([+ { index: 1, value: null },+ { index: 2, value: 'fox' },+ ]);+ });+});diff --git a/client/src/components/meatspace/post/PostSessionSummary.jsx b/client/src/components/meatspace/post/PostSessionSummary.jsxindex 10fff4f537..44aeef087d 100644--- a/client/src/components/meatspace/post/PostSessionSummary.jsx+++ b/client/src/components/meatspace/post/PostSessionSummary.jsx@@ -3,6 +3,16 @@ import { CheckCircle, ChevronDown, ChevronUp, Dumbbell } from 'lucide-react';import { LLM_DRILL_TYPES, DRILL_TO_DOMAIN, DOMAINS, DRILL_LABELS, nBackBalancedAccuracy } from './constants';import DrillQuestionReview from './DrillQuestionReview';+function fillBlankAttempts(questions) {+ return questions.flatMap(question => Array.isArray(question?.answered)+ ? question.answered.map(answer => ({+ answered: answer?.value ?? null,+ correct: answer?.correct,+ responseMs: question.responseMs,+ }))+ : [question]);+}+// Presentational session breakdown shared by the live post-save results screen// (PostSessionResults) and the deep-linkable saved-session view// (PostSessionDetail) — so a just-finished session and a revisited one from@@ -85,16 +95,22 @@ export default function PostSessionSummary({ drillResults = [], sessionScore = 0// (raw `correct` averaging would pay ~70% for never pressing).const questions = result.questions || [];const noGo = result.type === 'n-back';- const reached = noGo ? questions : questions.filter(q => q.answered !== null);+ const fillBlank = result.type === 'memory-fill-blank';+ const attempts = fillBlank ? fillBlankAttempts(questions) : questions;+ const reached = noGo || fillBlank ? attempts : questions.filter(q => q.answered !== null);const derivedAcc = noGo? nBackBalancedAccuracy(questions)- : (reached.length > 0 ? reached.filter(q => q.correct).length / reached.length : null);+ : (fillBlank+ ? (attempts.length > 0 ? attempts.filter(q => q.correct).length / attempts.length : null)+ : (reached.length > 0 ? reached.filter(q => q.correct).length / reached.length : null));const accPct = result.accuracy != null? Math.round(result.accuracy * 100): (derivedAcc != null ? Math.round(derivedAcc * 100) : null);const compPct = result.completion != null? Math.round(result.completion * 100)- : (questions.length > 0 ? Math.round((reached.length / questions.length) * 100) : null);+ : (fillBlank+ ? (attempts.length > 0 ? Math.round((reached.filter(q => q.answered != null).length / attempts.length) * 100) : null)+ : (questions.length > 0 ? Math.round((reached.length / questions.length) * 100) : null));const timed = reached.filter(q => q.responseMs > 0);const avgMs = result.avgResponseMs != null? result.avgResponseMsdiff --git a/client/src/components/meatspace/post/constants.js b/client/src/components/meatspace/post/constants.jsindex db41d704c8..e12057bcb5 100644--- a/client/src/components/meatspace/post/constants.js+++ b/client/src/components/meatspace/post/constants.js@@ -10,10 +10,9 @@ export const MEMORY_DRILL_TYPES = ['memory-fill-blank', 'memory-sequence', 'memoexport const COGNITIVE_DRILL_TYPES = ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time'];// Drill types valid elsewhere but not yet wired into the interactive POST-// session drill picker (DOMAINS.memory.drillTypes below) — memory-fill-blank's-// scoring path is fully correct now (see MEMORY_DRILL_TYPES above), it just-// isn't one of the types PostSessionLauncher offers to pick from yet.-export const POST_UNSUPPORTED_DRILL_TYPES = ['memory-fill-blank'];+// session drill picker. Multi-blank fill-in-the-blank is now wired end to end,+// so this remains empty until a future generation-only type needs the guard.+export const POST_UNSUPPORTED_DRILL_TYPES = [];// The server generators have item-shape requirements: Sequence Recall needs a// successor line, while Element Flash is backed by the built-in periodic-table@@ -171,9 +170,8 @@ export function isMemoryItemEnabled(config, itemId) {// 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.+// null module and is therefore not a domain. Generation-only types are filtered+// out here through POST_UNSUPPORTED_DRILL_TYPES.export const DOMAINS = Object.fromEntries(POST_TOPICS.filter(t => t.module)diff --git a/client/src/components/meatspace/post/constants.test.js b/client/src/components/meatspace/post/constants.test.jsindex a5df5455b9..30449cb6c2 100644--- a/client/src/components/meatspace/post/constants.test.js+++ b/client/src/components/meatspace/post/constants.test.js@@ -129,12 +129,10 @@ describe('POST_TOPICS → DOMAINS derivation (issue #3252)', () => {}});- 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.+ it('includes the completed multi-blank recall drill in the session picker', () => {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();+ expect(DOMAINS.memory.drillTypes).toEqual(['memory-fill-blank', 'memory-sequence', 'memory-element-flash']);+ expect(DRILL_TO_DOMAIN['memory-fill-blank']).toBe('memory');});it('maps every domain drill type back to its domain', () => {@@ -203,7 +201,7 @@ describe('composedSessionDrillTypes (issue #3252)', () => {expect(composedSessionDrillTypes(memoryConfig, [{ id: 'elements-song', content: { lines: [{ text: 'Hydrogen' }, { text: 'Helium' }] } },{ id: 'example-memory', content: { lines: [{ text: 'First' }, { text: 'Second' }] } },- ])).toEqual({ memory: ['memory-sequence'] });+ ])).toEqual({ memory: ['memory-fill-blank', 'memory-sequence'] });expect(composedSessionDrillTypes(memoryConfig, [])).toEqual({});});diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.jsindex 91385fd5c2..a2379719a3 100644--- a/client/src/hooks/usePostSession.js+++ b/client/src/hooks/usePostSession.js@@ -78,6 +78,72 @@ function memoryAttribution(q) {return attrs;}+function normalizeFillBlankValue(value) {+ return String(value ?? '').toLowerCase().trim();+}++function fillBlankAnswerKeys(question) {+ return (question?.answers || []).map((answer, fallbackIndex) => ({+ index: Number.isInteger(answer?.index) ? answer.index : fallbackIndex,+ expected: String(answer?.word ?? answer),+ ...(answer?.element != null ? { element: answer.element } : {}),+ }));+}++/**+ * Build one response for every generated blank. A scalar value is the legacy+ * client contract: match it to one indexed blank and never let it satisfy the+ * whole prompt. Structured values are keyed by answer index and missing values+ * remain explicit misses so the server can derive partial credit consistently.+ */+export function buildFillBlankAnswerEntries(question, value) {+ const keys = fillBlankAnswerKeys(question);+ if (!keys.length) return [];++ if (Array.isArray(value) || value === null) {+ const submitted = new Map((Array.isArray(value) ? value : keys.map(key => ({ index: key.index, value: null })))+ .map(entry => [entry?.index, entry?.value]));+ return keys.map(key => {+ const raw = submitted.get(key.index);+ const answered = raw == null || String(raw).trim() === '' ? null : String(raw).trim();+ return {+ index: key.index,+ value: answered,+ expected: key.expected,+ correct: answered !== null && normalizeFillBlankValue(answered) === normalizeFillBlankValue(key.expected),+ ...(key.element == null ? {} : { element: key.element }),+ };+ });+ }++ const answered = value == null || String(value).trim() === '' ? null : String(value).trim();+ const matched = answered === null+ ? null+ : keys.find(key => normalizeFillBlankValue(key.expected) === normalizeFillBlankValue(answered));+ const target = matched || keys[0];+ return [{+ index: target.index,+ value: answered,+ expected: target.expected,+ correct: matched != null,+ ...(matched?.element == null ? {} : { element: matched.element }),+ }];+}++function hasAnsweredValue(value) {+ if (Array.isArray(value)) return value.some(entry => entry?.value != null && String(entry.value).trim() !== '');+ return value !== null && value !== undefined;+}++/** Count fill-blank credit by generated blank, with scalar legacy fallback. */+export function countFillBlankAnswers(answers = []) {+ const entries = answers.flatMap(answer => Array.isArray(answer?.answered) ? answer.answered : [answer]);+ return {+ correct: entries.filter(entry => entry?.correct).length,+ total: entries.length,+ };+}+// States: idle → loading → drilling → between-drills → complete → saving → savedconst STATES = {IDLE: 'idle',@@ -187,11 +253,16 @@ export function usePostSession() {const totalMs = Date.now() - drillStartRef.current;const timeLimitMs = (currentDrill?.timeLimitSec || 120) * 1000;- // Compute score- const correct = finalAnswers.filter(a => a.correct).length;- const total = finalAnswers.length;+ // Compute score. Multi-blank recall earns one unit per generated blank;+ // question-level correctness remains an all-blanks pass/fail flag for+ // review display and legacy readers.+ const isFillBlank = currentDrill.type === 'memory-fill-blank';+ const scored = isFillBlank+ ? countFillBlankAnswers(finalAnswers)+ : { correct: finalAnswers.filter(a => a.correct).length, total: finalAnswers.length };+ const { correct, total } = scored;const correctRatio = total > 0 ? correct / total : 0;- const answered = finalAnswers.filter(a => a.answered !== null);+ const answered = finalAnswers.filter(a => hasAnsweredValue(a.answered));const totalResponseMs = answered.reduce((sum, a) => sum + a.responseMs, 0);const avgResponseMs = answered.length > 0 ? totalResponseMs / answered.length : timeLimitMs;const speedBonus = Math.max(0, 1 - avgResponseMs / timeLimitMs);@@ -240,23 +311,10 @@ export function usePostSession() {// For estimation drills, check within tolerancelet correct;let answered;- // Fill-blank element attribution: which specific answers[] entry the- // user's guess matched (if any) — set only on an unambiguous correct- // match, since a wrong guess against a multi-blank prompt can't be- // attributed to any one blank/element (issue #2099 codex review).- let matchedElement;if (hasFillBlankAnswers) {- answered = value;- const normalized = value !== null ? String(value).toLowerCase().trim() : '';- // q.answers holds ACCEPTABLE-WORD OBJECTS ({ index, word, element }), not- // scalars — comparing via String(a) on an object always produced- // "[object Object]" so this could never match, silently scoring every- // fill-blank answer wrong (issue #2116). Compare against the object's- // `.word` (falling back to the raw value for a plain-string entry, for- // forward/backward compatibility with any other producer).- const matched = q.answers.find(a => String(a?.word ?? a).toLowerCase().trim() === normalized);- correct = !!matched;- matchedElement = matched?.element ?? null;+ const entries = buildFillBlankAnswerEntries(q, value);+ answered = entries;+ correct = entries.length > 0 && entries.every(entry => entry.correct);} else if (isTextAnswer) {answered = value;correct = value !== null && String(value).toLowerCase().trim() === String(q.expected).toLowerCase().trim();@@ -278,11 +336,6 @@ export function usePostSession() {correct,responseMs,...memoryAttribution(q),- // Fill-blank's per-answer element (see matchedElement above) takes- // priority over memoryAttribution(q)'s question-level element field- // (which fill-blank questions never carry — only memory-element-flash- // does), so mergeMasteryFromSession can credit the matched element.- ...(matchedElement != null ? { element: matchedElement } : {})};const newAnswers = [...answers, answer];@@ -343,14 +396,18 @@ export function usePostSession() {if (state !== STATES.DRILLING || !currentDrill) return;// Mark remaining questions as unanswered- const remaining = (currentDrill.questions || []).slice(currentQuestionIndex).map(q => ({- prompt: q.prompt,- expected: q.expected,- answered: null,- correct: false,- responseMs: 0,- ...memoryAttribution(q)- }));+ const remaining = (currentDrill.questions || []).slice(currentQuestionIndex).map(q => {+ const hasFillBlankAnswers = Array.isArray(q.answers) && q.answers.length > 0;+ const answered = hasFillBlankAnswers ? buildFillBlankAnswerEntries(q, null) : null;+ return {+ prompt: q.prompt,+ expected: q.expected,+ answered,+ correct: false,+ responseMs: 0,+ ...memoryAttribution(q)+ };+ });const finalAnswers = [...answers, ...remaining];setAnswers(finalAnswers);diff --git a/client/src/hooks/usePostSession.test.js b/client/src/hooks/usePostSession.test.jsindex 9ebed48009..f37c2da500 100644--- a/client/src/hooks/usePostSession.test.js+++ b/client/src/hooks/usePostSession.test.js@@ -282,7 +282,7 @@ describe('usePostSession — memory-fill-blank scoring (issue #2099/#2116)', ()};}- it('marks a fill-blank answer correct when it matches an acceptable answer word', async () => {+ it('marks a single-blank answer correct and preserves its index', async () => {generatePostDrill.mockResolvedValue(fillBlankDrill([{ index: 1, word: 'quick', element: null }]));@@ -297,11 +297,14 @@ describe('usePostSession — memory-fill-blank scoring (issue #2099/#2116)', ()const task = result.current.drillResults[0];expect(task.questions[0].correct).toBe(true);+ expect(task.questions[0].answered).toEqual([+ { index: 1, value: 'quick', expected: 'quick', correct: true },+ ]);expect(task.module).toBe('memory');expect(task.memoryItemId).toBe('song-1');});- it('is case/whitespace-insensitive, matching any of several acceptable blanked words', async () => {+ it('scores every generated blank instead of treating one matching word as full credit', async () => {generatePostDrill.mockResolvedValue(fillBlankDrill([{ index: 1, word: 'quick', element: null },@@ -314,10 +317,15 @@ describe('usePostSession — memory-fill-blank scoring (issue #2099/#2116)', ()await result.current.startSession([{ type: 'memory-fill-blank', config: {}, timeLimitSec: 60 }]);});act(() => {- result.current.submitAnswer(' FOX ');+ result.current.submitAnswer([{ index: 2, value: ' FOX ' }]);});- expect(result.current.drillResults[0].questions[0].correct).toBe(true);+ const question = result.current.drillResults[0].questions[0];+ expect(question.correct).toBe(false);+ expect(question.answered).toEqual([+ { index: 1, value: null, expected: 'quick', correct: false },+ { index: 2, value: 'FOX', expected: 'fox', correct: true },+ ]);});it('marks a fill-blank answer incorrect when it matches none of the acceptable words', async () => {@@ -336,13 +344,9 @@ describe('usePostSession — memory-fill-blank scoring (issue #2099/#2116)', ()expect(result.current.drillResults[0].questions[0].correct).toBe(false);});- // Regression (codex review of issue #2099): a correct fill-blank match on- // an element-name blank must carry that element through to the answer so- // mergeMasteryFromSession can credit item.mastery.elements — previously- // only chunkId (question-level) survived; the per-answer element was- // silently dropped because memoryAttribution(q) only reads q.element,- // which fill-blank questions never carry (only answers[i].element does).- it('attributes the matched answer\'s element on a correct match', async () => {+ // Element attribution follows the indexed blank, while the question remains+ // partial until every generated answer is supplied.+ it('attributes indexed answer elements independently', async () => {generatePostDrill.mockResolvedValue(fillBlankDrill([{ index: 1, word: 'hydrogen', element: 'H' },@@ -355,12 +359,14 @@ describe('usePostSession — memory-fill-blank scoring (issue #2099/#2116)', ()await result.current.startSession([{ type: 'memory-fill-blank', config: {}, timeLimitSec: 60 }]);});act(() => {- result.current.submitAnswer('hydrogen');+ result.current.submitAnswer([{ index: 1, value: 'hydrogen' }]);});const q = result.current.drillResults[0].questions[0];- expect(q.correct).toBe(true);- expect(q.element).toBe('H');+ expect(q.correct).toBe(false);+ expect(q.element).toBeUndefined();+ expect(q.answered[0]).toMatchObject({ index: 1, value: 'hydrogen', expected: 'hydrogen', correct: true, element: 'H' });+ expect(q.answered[1]).toMatchObject({ index: 3, value: null, expected: 'fox', correct: false });});it('omits element on an incorrect match — which blank was intended is ambiguous', async () => {@@ -379,6 +385,7 @@ describe('usePostSession — memory-fill-blank scoring (issue #2099/#2116)', ()const q = result.current.drillResults[0].questions[0];expect(q.correct).toBe(false);expect(q).not.toHaveProperty('element');+ expect(q.answered).toEqual([{ index: 1, value: 'nope', expected: 'hydrogen', correct: false }]);});it('omits element when the matched answer has none (a plain-word blank)', async () => {@@ -397,6 +404,7 @@ describe('usePostSession — memory-fill-blank scoring (issue #2099/#2116)', ()const q = result.current.drillResults[0].questions[0];expect(q.correct).toBe(true);expect(q).not.toHaveProperty('element');+ expect(q.answered[0]).toEqual({ index: 1, value: 'quick', expected: 'quick', correct: true });// chunkId still comes through via memoryAttribution(q) regardless.expect(q.chunkId).toBe('verse-1');});diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex 9fec0f51fd..21f22c5e9e 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -18,6 +18,17 @@ export const postTagsSchema = z.record(z.string().max(200));// Individual question result (math + memory drills)// Math: server recomputes expected/correct via scoreDrill (numeric values)// Memory: client scores with string comparison (text values)+const fillBlankAnswerSchema = z.object({+ // `index` is the source question's answer index, not the position in the+ // submitted array. Keeping it stable makes partial answers attributable even+ // when a client submits them out of order.+ index: z.number().int().min(0),+ value: z.string().nullable(),+ expected: z.string().optional(),+ correct: z.boolean().optional(),+ element: z.string().nullable().optional(),+});+const questionResultSchema = z.object({prompt: z.string(),// Cognitive drills key each trial back to its position in the generated@@ -25,7 +36,10 @@ const questionResultSchema = z.object({// server can recompute the answer key. Absent for math/memory drills.index: z.number().int().min(0).optional(),expected: z.union([z.number(), z.string()]).optional(),- answered: z.union([z.number(), z.string()]).nullable(),+ // Fill-blank now submits one indexed entry per generated blank. The scalar+ // forms remain valid for old clients and are intentionally treated as one+ // attributable attempt by the memory service, never as a full prompt pass.+ answered: z.union([z.number(), z.string(), z.array(fillBlankAnswerSchema)]).nullable(),correct: z.boolean().optional(),responseMs: z.number().min(0),// Reaction-time drill only: player pressed before the stimulus appeared.@@ -414,12 +428,25 @@ const practiceResultSchema = z.object({export const memoryPracticeSchema = z.object({// `element-study` is the standalone flash-card study mode (ElementsSong.jsx) —- // logged like `learn`; it advances element mastery via results[].element but- // is NOT a POST-session drill type (no server generator, see generateMemoryDrill).+ // logged like `learn` and intentionally does not advance mastery. It is NOT a+ // POST-session drill type (no server generator, see generateMemoryDrill).mode: z.enum(['fill-blank', 'sequence', 'element-flash', 'element-study', 'learn', 'speed-run']),chunkId: z.string().nullable().optional(),- results: z.array(practiceResultSchema).min(1),+ // Learn mode is an exposure event and legitimately has no scored results.+ // Every retrieval mode still needs at least one result.+ results: z.array(practiceResultSchema),totalMs: z.number().min(0).optional(),+}).superRefine((value, ctx) => {+ if (!['learn', 'element-study'].includes(value.mode) && value.results.length === 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.too_small,+ minimum: 1,+ inclusive: true,+ origin: 'array',+ path: ['results'],+ message: 'Retrieval practice requires at least one result',+ });+ }});export const memoryMasteryAttestationSchema = z.object({diff --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.jsindex 464da8c735..c96ec7c868 100644--- a/server/lib/postValidation.test.js+++ b/server/lib/postValidation.test.js@@ -218,6 +218,29 @@ describe('questionResultSchema chunkId/element (issue #2016)', () => {});expect(parsed.tasks[0].questions[0].chunkId).toBeNull();});++ it('accepts and preserves indexed multi-blank responses', () => {+ const parsed = postSessionSubmitSchema.parse({+ modules: ['memory'],+ tasks: [{+ module: 'memory',+ type: 'memory-fill-blank',+ questions: [{+ prompt: 'The ____ ____',+ expected: 'quick',+ answered: [+ { index: 1, value: 'quick', expected: 'quick', correct: true },+ { index: 2, value: 'slow', expected: 'fox', correct: false },+ ],+ correct: false,+ responseMs: 800,+ }],+ totalMs: 800,+ }],+ });+ expect(parsed.tasks[0].questions[0].answered).toHaveLength(2);+ expect(parsed.tasks[0].questions[0].answered[1].index).toBe(2);+ });});describe('postSessionSubmitSchema Schulte evidence metrics', () => {@@ -496,6 +519,11 @@ describe('memoryPracticeSchema mode enums', () => {expect(parsed.chunkId).toBeNull();expect(parsed.totalMs).toBe(4000);});++ it('accepts an empty result list for passive learn exposure', () => {+ expect(memoryPracticeSchema.parse({ mode: 'learn', results: [] }).results).toEqual([]);+ expect(memoryPracticeSchema.parse({ mode: 'element-study', results: [] }).results).toEqual([]);+ });});describe('postSessionSubmitSchema client-generated id (issue #2098)', () => {diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex dbee69c19d..bbd90e6e84 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -28,7 +28,14 @@ import {COGNITIVE_MASTERY_DEFAULTS,} from '../lib/postProgression.js';import { COGNITIVE_DRILL_TYPES, generateCognitiveDrill, scoreCognitiveDrill } from './meatspacePostCognitive.js';-import { applySessionToMemoryItems, getMemoryItems, getDueMemoryItems, MASTERY_TARGET_ACCURACY } from './meatspacePostMemory.js';+import {+ applySessionToMemoryItems,+ getMemoryItems,+ getDueMemoryItems,+ expandMemoryQuestionResults,+ normalizeMemoryQuestionResults,+ MASTERY_TARGET_ACCURACY,+} from './meatspacePostMemory.js';import { applySessionToReviewSchedule, getDueReviews, getRetentionReport } from './meatspacePostReview.js';// From postTrainingLogStore.js (NOT meatspacePostTraining.js) — that module// imports getUnifiedActivityStreak from postActivityStreak.js, which in turn@@ -304,9 +311,17 @@ export async function submitPostSession(sessionData) {// Memory drills: trust client-side scoring only for supported typesif (POST_SUPPORTED_MEMORY_TYPES.includes(rest.type)) {- return { ...rest, score: t.score || 0 };+ return {+ ...rest,+ // Multi-blank fill-in-the-blank results carry one indexed response per+ // generated blank. Recompute the question-level flag before storing so+ // history and later readers cannot turn one correct blank into a full+ // prompt pass.+ questions: normalizeMemoryQuestionResults(rest.questions || []),+ score: t.score || 0,+ };}- // Unsupported memory drills (e.g. memory-fill-blank): preserve data, zero score+ // Unsupported memory drills: preserve data, zero score.if (MEMORY_DRILL_TYPES.includes(rest.type)) {return { ...rest, score: 0 };}@@ -381,8 +396,8 @@ export async function submitPostSession(sessionData) {// try/catch: the session is already saved; there is nothing to roll back.)if (isNewSession) {// Pre-filter to POST-supported memory tasks with a memoryItemId — the exact- // gate the prior per-task loop used, so an unsupported memory drill (e.g.- // memory-fill-blank) is never scheduled even if it somehow carried an id.+ // gate the prior per-task loop used, so a future generation-only memory+ // drill is never scheduled even if it somehow carries an id.const memoryTasks = rescoredTasks.filter(t => POST_SUPPORTED_MEMORY_TYPES.includes(t.type) && t.memoryItemId);try {await applySessionToMemoryItems(memoryTasks, new Date(now));@@ -620,6 +635,10 @@ export function deriveTaskAccuracy(task) {// (otherwise a legacy never-press run still reads ~70%). Mirrors the client// fallbacks in PostHistory/PostSessionResults.if (task?.type === 'n-back') return nBackBalancedAccuracy(qs);+ if (task?.type === 'memory-fill-blank') {+ const attempts = expandMemoryQuestionResults(qs);+ return attempts.length ? attempts.filter(q => q?.correct).length / attempts.length : null;+ }const answered = qs.filter(q => q?.answered != null);if (!answered.length) return null;return answered.filter(q => q?.correct).length / answered.length;@@ -635,6 +654,11 @@ export function deriveTaskCompletion(task) {const qs = Array.isArray(task?.questions) ? task.questions : [];if (!qs.length) return null;if (task?.type === 'n-back') return 1;+ if (task?.type === 'memory-fill-blank') {+ const attempts = expandMemoryQuestionResults(qs);+ if (!attempts.length) return null;+ return attempts.filter(q => q?.answered != null).length / attempts.length;+ }return qs.filter(q => q?.answered != null).length / qs.length;}diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.jsindex 4f02fbe2eb..bbf3313bb6 100644--- a/server/services/meatspacePost.test.js+++ b/server/services/meatspacePost.test.js@@ -758,6 +758,44 @@ describe('submitPostSession — memory drill schedule advance', () => {const updatedMastery = masteryWrite[1].items.find(i => i.id === 'song-1');expect(updatedMastery.mastery.chunks['verse-1']).toEqual({ correct: 1, attempts: 1, lastPracticed: expect.any(String), recent: [1] });});++ it('scores each generated fill-blank independently and never promotes from one partial match', async () => {+ const session = await submitPostSession({+ cadence: 'daily',+ modules: ['memory'],+ tasks: [{+ module: 'memory',+ type: 'memory-fill-blank',+ memoryItemId: 'song-1',+ questions: [{+ prompt: 'The ____ ____',+ expected: 'quick',+ answered: [+ { index: 1, value: 'quick', expected: 'quick', correct: true },+ { index: 2, value: 'slow', expected: 'fox', correct: false },+ { index: 3, value: 'late', expected: 'runner', correct: false },+ ],+ correct: true,+ responseMs: 500,+ chunkId: 'verse-1',+ }],+ score: 50,+ totalMs: 500,+ }],+ tags: {},+ });++ expect(session.tasks[0].questions[0].correct).toBe(false);+ const memoryWrite = atomicWrite.mock.calls.find(([path]) => String(path).includes('post-memory-items'));+ const updatedItem = memoryWrite[1].items.find(i => i.id === 'song-1');+ expect(updatedItem.mastery.chunks['verse-1']).toEqual({+ correct: 1,+ attempts: 3,+ lastPracticed: expect.any(String),+ recent: [1, 0, 0],+ });+ expect(updatedItem.schedule.intervalDays).toBe(0);+ });});// =============================================================================@@ -1161,6 +1199,21 @@ describe('deriveTaskAccuracy / deriveTaskCompletion — legacy-session fallback'expect(deriveTaskCompletion(task)).toBeCloseTo(2 / 3, 5);});+ it('derives multi-blank accuracy and completion from indexed blank attempts', () => {+ const task = {+ type: 'memory-fill-blank',+ questions: [{+ answered: [+ { index: 1, value: 'quick', expected: 'quick', correct: true },+ { index: 2, value: null, expected: 'fox', correct: false },+ ],+ correct: false,+ }],+ };+ expect(deriveTaskAccuracy(task)).toBe(0.5);+ expect(deriveTaskCompletion(task)).toBe(0.5);+ });+it('returns null (never NaN) when there is nothing to derive from', () => {expect(deriveTaskAccuracy({ questions: [] })).toBe(null);expect(deriveTaskAccuracy({ questions: [{ answered: null }] })).toBe(null);diff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.jsindex 608c107e47..c8cc164645 100644--- a/server/services/meatspacePostMemory.js+++ b/server/services/meatspacePostMemory.js@@ -528,6 +528,11 @@ export async function deleteMemoryItem(id) {// PRACTICE & MASTERY// =============================================================================+// Only these modes are scored retrieval. Learn, flash-card study, and other+// non-scored surfaces may record time/activity, but must never promote mastery+// or move the spaced-repetition schedule from a self-reported exposure.+const RETRIEVAL_PRACTICE_MODES = new Set(['spaced', 'sequence', 'fill-blank', 'element-flash']);+function recordChunkResults(item, chunkId, results, nowIso) {if (!item.mastery.chunks[chunkId]) {item.mastery.chunks[chunkId] = { correct: 0, attempts: 0, lastPracticed: null };@@ -540,12 +545,58 @@ function recordChunkResults(item, chunkId, results, nowIso) {preserveStatMastery(chunk, nowIso);}+async function saveMemoryPracticeRun({ memoryItemId, mode, chunkId, results, totalMs, date, timestamp, exposure = false }) {+ const practiceId = randomUUID();+ const runId = `memory-practice:${practiceId}`;+ const correctCount = results.filter(result => result.correct).length;+ const record = {+ id: practiceId,+ runId,+ memoryItemId,+ mode,+ chunkId: chunkId || null,+ totalMs: totalMs || 0,+ date,+ timestamp,+ ...(exposure ? {} : {+ correct: correctCount,+ total: results.length,+ }),+ inputMode: 'unknown',+ scorerProvenance: 'memory-practice',+ };+ await saveStoredTrainingRun({+ id: runId,+ mode: 'training',+ localDay: date,+ startedAt: timestamp,+ completedAt: timestamp,+ status: 'completed',+ planned: { modules: ['memory'] },+ data: { id: runId, mode: 'training' },+ attempts: [{+ id: practiceId,+ module: 'memory',+ drillType: mode || 'unknown',+ correct: exposure || results.length === 0 ? null : correctCount === results.length,+ score: exposure || results.length === 0 ? null : (correctCount / results.length) * 100,+ latencyMs: totalMs || 0,+ completion: exposure || results.length === 0 ? null : 1,+ hintUsed: !exposure && results.some(result => result?.hintUsed === true),+ inputMode: 'unknown',+ scorerProvenance: 'memory-practice',+ data: record,+ }],+ });+ return practiceId;+}+export async function submitPractice(id, practiceData) {const items = await loadMemoryItems();const item = items.find(i => i.id === id);if (!item) return null;- const { mode, chunkId, results, totalMs } = practiceData;+ const { mode, chunkId, results = [], totalMs } = practiceData;const nowDate = new Date();const now = nowDate.toISOString();// Day-key in the user's local timezone (issue #2681): this practice is a@@ -556,6 +607,26 @@ export async function submitPractice(id, practiceData) {// keeps the exact instant, matching submitTrainingEntry's shape. Derive the day// from the SAME `nowDate` so a midnight boundary can't split date and timestamp.const todayLocal = await userLocalToday(nowDate);++ // Passive study is activity, not retrieval. Keep the event for time/streak+ // reporting, but do not touch mastery, retention, schedule, or correctness.+ // This also makes old clients that sent a synthetic `{ correct: true }` learn+ // result harmless: the service ignores the payload entirely in this branch.+ if (!RETRIEVAL_PRACTICE_MODES.has(mode)) {+ const practiceId = await saveMemoryPracticeRun({+ memoryItemId: id,+ mode,+ chunkId: null,+ results,+ totalMs,+ date: todayLocal,+ timestamp: now,+ exposure: true,+ });+ console.log(`🧠 Memory exposure logged: "${item.title}" mode=${mode}`);+ return { mastery: item.mastery, schedule: item.schedule, practiceId };+ }+const correctCount = results.filter(r => r.correct).length;const ratio = results.length ? correctCount / results.length : 0;const spotCheckDue = isMemorySpotCheckDue(item, nowDate);@@ -617,44 +688,14 @@ export async function submitPractice(id, practiceData) {await saveMemoryItems(items);// Log the practice session- const practiceId = randomUUID();- const runId = `memory-practice:${practiceId}`;- const record = {- id: practiceId,- runId,+ const practiceId = await saveMemoryPracticeRun({memoryItemId: id,mode,- chunkId: chunkId || null,- correct: results.filter(r => r.correct).length,- total: results.length,- totalMs: totalMs || 0,+ chunkId,+ results,+ totalMs,date: todayLocal,timestamp: now,- inputMode: 'unknown',- scorerProvenance: 'memory-practice',- };- await saveStoredTrainingRun({- id: runId,- mode: 'training',- localDay: todayLocal,- startedAt: now,- completedAt: now,- status: 'completed',- planned: { modules: ['memory'] },- data: { id: runId, mode: 'training' },- attempts: [{- id: practiceId,- module: 'memory',- drillType: mode || 'unknown',- correct: results.length > 0 ? correctCount === results.length : null,- score: results.length > 0 ? (correctCount / results.length) * 100 : null,- latencyMs: totalMs || 0,- completion: results.length > 0 ? 1 : null,- hintUsed: results.some((result) => result?.hintUsed === true),- inputMode: 'unknown',- scorerProvenance: 'memory-practice',- data: record,- }],});console.log(`🧠 Practice logged: "${item.title}" mode=${mode} ${correctCount}/${results.length} → next review in ${item.schedule.intervalDays}d`);@@ -671,8 +712,8 @@ export async function submitPractice(id, practiceData) {* result data `submitPractice` uses for that.** Returns the updated schedule, or `null` when `memoryItemId` is absent or- * doesn't match a known item (unsupported memory drills like- * `memory-fill-blank` carry no memoryItemId — see POST_SUPPORTED_MEMORY_TYPES).+ * doesn't match a known item. The composed-session path uses+ * `applySessionToMemoryItems`, which gates tasks to scored retrieval types.*/export async function advanceScheduleFromSession(memoryItemId, ratio, now = new Date()) {if (!memoryItemId) return null;@@ -708,6 +749,62 @@ function applyScheduleAdvanceToItem(item, ratio, now) {return item.schedule;}+function normalizeFillBlankValue(value) {+ return String(value ?? '').toLowerCase().trim();+}++/**+ * Expand the indexed answer list introduced for multi-blank recall into the+ * per-blank attempts used by mastery and scheduling. A legacy scalar question+ * deliberately remains one attempt, even if its generated prompt once had+ * several hidden words.+ */+export function expandMemoryQuestionResults(questions = []) {+ return (Array.isArray(questions) ? questions : []).flatMap(question => {+ if (!Array.isArray(question?.answered)) return [question];+ return question.answered.map(answer => {+ const answered = answer?.value ?? null;+ // New clients send the answer key with each indexed response. For a+ // one-entry legacy structured payload, the question-level expected value+ // is a safe fallback; never apply a scalar key to every blank.+ const expected = answer?.expected ?? (+ question.answered.length === 1 && typeof question.expected === 'string'+ ? question.expected+ : undefined+ );+ const correct = typeof expected === 'string'+ ? answered !== null && normalizeFillBlankValue(answered) === normalizeFillBlankValue(expected)+ : Boolean(answer?.correct);+ return {+ ...question,+ expected,+ answered,+ correct,+ ...(answer?.element !== undefined ? { element: answer.element } : {}),+ };+ });+ });+}++/** Recompute question-level correctness for persisted multi-blank results. */+export function normalizeMemoryQuestionResults(questions = []) {+ return (Array.isArray(questions) ? questions : []).map(question => {+ if (!Array.isArray(question?.answered)) return question;+ const attempts = expandMemoryQuestionResults([question]);+ return {+ ...question,+ answered: question.answered.map((answer, index) => ({+ ...answer,+ value: attempts[index]?.answered ?? null,+ ...(attempts[index]?.expected !== undefined ? { expected: attempts[index].expected } : {}),+ correct: attempts[index]?.correct ?? false,+ ...(attempts[index]?.element !== undefined ? { element: attempts[index].element } : {}),+ })),+ correct: attempts.length > 0 && attempts.every(attempt => attempt.correct),+ };+ });+}+// In-place mastery merge shared by mergeMasteryFromSession and// applySessionToMemoryItems — same single-core-of-truth rationale as// applyScheduleAdvanceToItem above.@@ -778,10 +875,12 @@ export async function mergeMasteryFromSession(memoryItemId, questions, now = newconst item = items.find(i => i.id === memoryItemId);if (!item) return null;- applyMasteryMergeToItem(item, questions, now);+ const attempts = expandMemoryQuestionResults(questions);+ if (!attempts.length) return null;+ applyMasteryMergeToItem(item, attempts, now);await saveMemoryItems(items);- console.log(`🧠 POST session mastery merged: "${item.title}" ${questions.length} answers → ${item.mastery.overallPct}% overall`);+ console.log(`🧠 POST session mastery merged: "${item.title}" ${attempts.length} answers → ${item.mastery.overallPct}% overall`);return item.mastery;}@@ -798,7 +897,10 @@ export async function mergeMasteryFromSession(memoryItemId, questions, now = new* @returns {Promise<{updated:number}>} how many memory items were touched*/export async function applySessionToMemoryItems(tasks, now = new Date()) {- const memoryTasks = (Array.isArray(tasks) ? tasks : []).filter(t => t?.memoryItemId);+ const memoryTasks = (Array.isArray(tasks) ? tasks : []).filter(t => (+ t?.memoryItemId+ && (!t.type || ['memory-fill-blank', 'memory-sequence', 'memory-element-flash'].includes(t.type))+ ));if (!memoryTasks.length) return { updated: 0 };const items = await loadMemoryItems();@@ -806,7 +908,7 @@ export async function applySessionToMemoryItems(tasks, now = new Date()) {for (const task of memoryTasks) {const item = items.find(i => i.id === task.memoryItemId);if (!item) continue;- const questions = Array.isArray(task.questions) ? task.questions : [];+ const questions = expandMemoryQuestionResults(task.questions);const total = questions.length;const correct = questions.filter(q => q?.correct).length;const ratio = total ? correct / total : 0;@@ -956,11 +1058,9 @@ function generateFillBlank(item, count) {prompt: display,fullText: line.text,// Scalar primary answer (the first blanked word) — kept alongside the- // full `answers[]` acceptable-word list so consumers that expect a- // single `expected` field (DrillQuestionReview, scoring) have a- // consistent value instead of always reading "—"/undefined (issue- // #2116). Scoring still checks `answers[]` for a match against ANY- // blanked word, not just this primary one.+ // indexed `answers[]` key for legacy consumers. New POST clients render+ // and submit every entry; a scalar response remains a one-blank legacy+ // attempt rather than a full-prompt pass.expected: answers[0]?.word ?? null,answers,chunkId: findChunkForLine(item, lines.indexOf(line)),diff --git a/server/services/meatspacePostMemory.test.js b/server/services/meatspacePostMemory.test.jsindex 3ecd39aa5a..09d94ccb5c 100644--- a/server/services/meatspacePostMemory.test.js+++ b/server/services/meatspacePostMemory.test.js@@ -481,6 +481,27 @@ describe('submitPractice', () => {expect(result.mastery.chunks['verse-1'].lastPracticed).toBeTruthy();});+ it('records learn as exposure without changing mastery, schedule, or correctness', async () => {+ const result = await submitPractice('elements-song', {+ mode: 'learn',+ chunkId: 'verse-1',+ // Accept the legacy synthetic success too; passive study must ignore it.+ results: [{ correct: true, element: 'H' }],+ totalMs: 12000,+ });++ expect(result.mastery.overallPct).toBe(0);+ expect(result.mastery.elements).toEqual({});+ expect(result.schedule.lastReviewed).toBeNull();+ expect(atomicWrite.mock.calls.some(([path]) => String(path).includes('post-memory-items'))).toBe(false);++ const trainingWrite = atomicWrite.mock.calls.find(([path]) => String(path).includes('post-training-log'));+ expect(trainingWrite).toBeTruthy();+ expect(trainingWrite[1].entries.at(-1)).toMatchObject({ mode: 'learn', totalMs: 12000 });+ expect(trainingWrite[1].entries.at(-1)).not.toHaveProperty('correct');+ expect(trainingWrite[1].entries.at(-1)).not.toHaveProperty('total');+ });+it('stamps the training-log entry date in the user local timezone (issue #2681)', async () => {// 2026-07-16T05:00Z = 2026-07-15 22:00 PDT — UTC day July 16, LA day July 15.// The logged practice must key off the local day so it counts toward today's@@ -734,6 +755,34 @@ describe('applySessionToMemoryItems (consolidated one-pass, issue #2098)', () =>expect(written.mastery.elements).toEqual(legacyMastery.elements);expect(written.mastery.overallPct).toEqual(legacyMastery.overallPct);});++ it('counts every indexed fill-blank response as its own mastery attempt', async () => {+ readJSONFile.mockResolvedValueOnce({ items: [seedItem()] });+ await applySessionToMemoryItems([{+ type: 'memory-fill-blank',+ memoryItemId: 'elements-song',+ questions: [{+ prompt: 'The ____ ____',+ expected: 'quick',+ answered: [+ { index: 1, value: 'quick', expected: 'quick', correct: true },+ { index: 2, value: 'slow', expected: 'fox', correct: false },+ { index: 3, value: 'late', expected: 'runner', correct: false },+ ],+ correct: false,+ chunkId: 'verse-1',+ }],+ }], now);++ const written = atomicWrite.mock.calls[0][1].items[0];+ expect(written.mastery.chunks['verse-1']).toEqual({+ correct: 1,+ attempts: 3,+ lastPracticed: now.toISOString(),+ recent: [1, 0, 0],+ });+ expect(written.schedule.intervalDays).toBe(0);+ });});// =============================================================================