Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: POST Memory Builder with Elements Song (M55 P1)

Adam Eivyc1063c62a9d5
diff --git a/client/src/components/meatspace/post/ElementsSong.jsx b/client/src/components/meatspace/post/ElementsSong.jsx
new file mode 100644
index 0000000000..21305cdb61
--- /dev/null
+++ b/client/src/components/meatspace/post/ElementsSong.jsx
@@ -0,0 +1,548 @@
+import { useState, useEffect, useRef } from 'react';
+import { ChevronLeft, Play, BookOpen, Zap, Target, Check, X, SkipForward } from 'lucide-react';
+import { submitMemoryPractice, getMemoryMastery } from '../../../services/api';
+
+// Standard periodic table layout: [row][col] = symbol or null
+const PERIODIC_TABLE = [
+ ['H', null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,'He'],
+ ['Li','Be', null,null,null,null,null,null,null,null,null,null,'B', 'C', 'N', 'O', 'F', 'Ne'],
+ ['Na','Mg', null,null,null,null,null,null,null,null,null,null,'Al','Si','P', 'S', 'Cl','Ar'],
+ ['K', 'Ca','Sc','Ti','V', 'Cr','Mn','Fe','Co','Ni','Cu','Zn','Ga','Ge','As','Se','Br','Kr'],
+ ['Rb','Sr','Y', 'Zr','Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn','Sb','Te','I', 'Xe'],
+ ['Cs','Ba','La','Hf','Ta','W', 'Re','Os','Ir','Pt','Au',null,'Tl','Pb','Bi','Po','At','Rn'],
+ ['Fr','Ra','Ac',null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],
+ // Lanthanides (Ce-Lu) and Actinides (Th-No) as separate rows
+ [null,null,null,'Ce','Pr','Nd','Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb','Lu',null],
+ [null,null,null,'Th','Pa','U', 'Np','Pu','Am','Cm','Bk','Cf','Es','Fm','Md','No',null,null],
+];
+
+const PRACTICE_MODES = [
+ { id: 'learn', label: 'Learn Lyrics', icon: BookOpen, desc: 'Read through the song verse by verse' },
+ { id: 'element-flash', label: 'Element Flash', icon: Zap, desc: 'Name elements from symbols or vice versa' },
+ { id: 'fill-blank', label: 'Fill the Lyrics', icon: Target, desc: 'Fill in missing element names from the lyrics' },
+];
+
+export default function ElementsSong({ item, onBack }) {
+ const [mastery, setMastery] = useState(item.mastery || { overallPct: 0, chunks: {}, elements: {} });
+ const [mode, setMode] = useState(null);
+
+ useEffect(() => {
+ getMemoryMastery(item.id).then(m => { if (m) setMastery(m); }).catch(() => {});
+ }, [item.id]);
+
+ function handlePracticeComplete(newMastery) {
+ if (newMastery) setMastery(newMastery);
+ setMode(null);
+ }
+
+ if (mode === 'learn') return <LearnMode item={item} onBack={() => setMode(null)} onComplete={handlePracticeComplete} />;
+ if (mode === 'element-flash') return <ElementFlashMode item={item} mastery={mastery} onBack={() => setMode(null)} onComplete={handlePracticeComplete} />;
+ if (mode === 'fill-blank') return <FillBlankMode item={item} onBack={() => setMode(null)} onComplete={handlePracticeComplete} />;
+
+ const elementMap = item.content?.elementMap || {};
+ const songElements = new Set();
+ for (const line of item.content?.lines || []) {
+ for (const sym of line.elements || []) songElements.add(sym);
+ }
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-center gap-3">
+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors">
+ <ChevronLeft size={20} />
+ </button>
+ <h2 className="text-xl font-bold text-white">The Elements Song</h2>
+ <span className="text-gray-500 text-sm ml-auto">Tom Lehrer</span>
+ </div>
+
+ {/* Mastery header */}
+ <div className="bg-port-card border border-port-border rounded-lg p-4 flex items-center justify-between">
+ <div>
+ <div className="text-gray-400 text-sm">Overall Mastery</div>
+ <div className={`text-2xl font-bold font-mono ${mastery.overallPct >= 80 ? 'text-port-success' : mastery.overallPct >= 40 ? 'text-port-warning' : 'text-gray-500'}`}>
+ {mastery.overallPct}%
+ </div>
+ </div>
+ <div className="text-right text-sm text-gray-500">
+ <div>{Object.keys(mastery.elements || {}).filter(s => { const m = mastery.elements[s]; return m?.attempts >= 3 && m.correct / m.attempts >= 0.8; }).length} / {Object.keys(elementMap).length} elements mastered</div>
+ <div>{Object.keys(elementMap).length} elements in song</div>
+ </div>
+ </div>
+
+ {/* Periodic Table Mastery Map */}
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <h3 className="text-sm font-medium text-gray-400 mb-3">Periodic Table Mastery</h3>
+ <div className="overflow-x-auto">
+ <div className="inline-grid gap-0.5" style={{ gridTemplateColumns: 'repeat(18, 1fr)', minWidth: '540px' }}>
+ {PERIODIC_TABLE.map((row, ri) =>
+ row.map((sym, ci) => {
+ if (!sym) return <div key={`${ri}-${ci}`} className="w-[30px] h-[30px]" />;
+ const inSong = songElements.has(sym);
+ const m = mastery.elements?.[sym];
+ const masteryPct = m?.attempts > 0 ? m.correct / m.attempts : 0;
+ const bg = !inSong ? 'bg-gray-800/30'
+ : masteryPct >= 0.8 && m.attempts >= 3 ? 'bg-emerald-600/60'
+ : masteryPct >= 0.5 ? 'bg-amber-600/50'
+ : m?.attempts > 0 ? 'bg-red-600/40'
+ : 'bg-port-border';
+ const textColor = !inSong ? 'text-gray-700' : 'text-white';
+
+ return (
+ <div
+ key={`${ri}-${ci}`}
+ className={`w-[30px] h-[30px] flex items-center justify-center text-[9px] font-mono rounded-sm ${bg} ${textColor} cursor-default`}
+ title={`${elementMap[sym]?.name || sym}${inSong ? ` (${m?.correct || 0}/${m?.attempts || 0})` : ' (not in song)'}`}
+ >
+ {sym}
+ </div>
+ );
+ })
+ )}
+ </div>
+ </div>
+ <div className="flex gap-4 mt-3 text-xs text-gray-500">
+ <span className="flex items-center gap-1"><span className="w-3 h-3 rounded-sm bg-emerald-600/60 inline-block" /> Mastered</span>
+ <span className="flex items-center gap-1"><span className="w-3 h-3 rounded-sm bg-amber-600/50 inline-block" /> Learning</span>
+ <span className="flex items-center gap-1"><span className="w-3 h-3 rounded-sm bg-red-600/40 inline-block" /> Needs work</span>
+ <span className="flex items-center gap-1"><span className="w-3 h-3 rounded-sm bg-port-border inline-block" /> Not started</span>
+ <span className="flex items-center gap-1"><span className="w-3 h-3 rounded-sm bg-gray-800/30 inline-block" /> Not in song</span>
+ </div>
+ </div>
+
+ {/* Practice Modes */}
+ <div className="space-y-3">
+ <h3 className="text-sm font-medium text-gray-400">Practice</h3>
+ {PRACTICE_MODES.map(m => (
+ <button
+ key={m.id}
+ onClick={() => setMode(m.id)}
+ className="w-full bg-port-card border border-port-border rounded-lg p-4 text-left hover:border-port-accent/50 transition-colors flex items-center gap-4"
+ >
+ <m.icon size={20} className="text-emerald-400 shrink-0" />
+ <div>
+ <div className="text-white font-medium">{m.label}</div>
+ <div className="text-gray-500 text-sm">{m.desc}</div>
+ </div>
+ </button>
+ ))}
+ </div>
+
+ {/* Verse breakdown */}
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <h3 className="text-sm font-medium text-gray-400 mb-3">Verses</h3>
+ <div className="space-y-3">
+ {(item.content?.chunks || []).map(chunk => {
+ const chunkMastery = mastery.chunks?.[chunk.id];
+ const pct = chunkMastery?.attempts > 0 ? Math.round((chunkMastery.correct / chunkMastery.attempts) * 100) : 0;
+ const lines = item.content.lines.slice(chunk.lineRange[0], chunk.lineRange[1] + 1);
+
+ return (
+ <details key={chunk.id} className="group">
+ <summary className="flex items-center justify-between cursor-pointer text-sm py-1 hover:text-white text-gray-300">
+ <span>{chunk.label}</span>
+ <span className={`font-mono text-xs ${pct >= 80 ? 'text-port-success' : pct > 0 ? 'text-port-warning' : 'text-gray-600'}`}>
+ {pct > 0 ? `${pct}%` : '—'}
+ </span>
+ </summary>
+ <div className="mt-2 ml-2 space-y-1">
+ {lines.map((line, i) => (
+ <div key={i} className="text-xs text-gray-500 leading-relaxed">{line.text}</div>
+ ))}
+ </div>
+ </details>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+// =============================================================================
+// LEARN MODE
+// =============================================================================
+
+function LearnMode({ item, onBack, onComplete }) {
+ const [currentChunk, setCurrentChunk] = useState(0);
+ const [revealedLines, setRevealedLines] = useState(1);
+ const chunks = item.content?.chunks || [];
+ const chunk = chunks[currentChunk];
+ const lines = chunk ? item.content.lines.slice(chunk.lineRange[0], chunk.lineRange[1] + 1) : [];
+
+ return (
+ <div className="space-y-6 max-w-2xl">
+ <div className="flex items-center gap-3">
+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors">
+ <ChevronLeft size={20} />
+ </button>
+ <h2 className="text-lg font-bold text-white">Learn — {chunk?.label || 'Elements Song'}</h2>
+ <span className="text-gray-500 text-sm ml-auto">{currentChunk + 1} / {chunks.length}</span>
+ </div>
+
+ <div className="w-full h-1.5 bg-port-border rounded-full overflow-hidden">
+ <div className="h-full bg-emerald-500 rounded-full transition-all" style={{ width: `${((currentChunk * 10 + revealedLines) / (chunks.length * 10)) * 100}%` }} />
+ </div>
+
+ <div className="bg-port-card border border-port-border rounded-lg p-6">
+ <div className="space-y-2">
+ {lines.map((line, i) => (
+ <div
+ key={i}
+ className={`text-sm leading-relaxed transition-all duration-300 ${
+ i < revealedLines ? (i === revealedLines - 1 ? 'text-white font-medium text-base' : 'text-gray-400') : 'text-transparent select-none'
+ }`}
+ >
+ {line.text}
+ {i < revealedLines && line.elements?.length > 0 && (
+ <span className="text-emerald-500/60 text-xs ml-2">
+ [{line.elements.join(', ')}]
+ </span>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="flex gap-3">
+ {revealedLines < lines.length ? (
+ <button
+ onClick={() => setRevealedLines(prev => prev + 1)}
+ className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ >
+ Reveal Next Line
+ </button>
+ ) : currentChunk < chunks.length - 1 ? (
+ <button
+ onClick={() => { setCurrentChunk(prev => prev + 1); setRevealedLines(1); }}
+ className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ >
+ Next Verse
+ </button>
+ ) : (
+ <button
+ onClick={() => {
+ submitMemoryPractice(item.id, {
+ mode: 'learn', chunkId: null,
+ results: [{ correct: true }],
+ totalMs: 0,
+ }).then(r => onComplete(r?.mastery)).catch(() => onComplete(null));
+ }}
+ 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} /> Complete
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// =============================================================================
+// ELEMENT FLASH MODE
+// =============================================================================
+
+function ElementFlashMode({ item, mastery, onBack, onComplete }) {
+ const elementMap = item.content?.elementMap || {};
+ const allElements = Object.entries(elementMap);
+
+ // Prioritize weak elements
+ const sorted = [...allElements].sort((a, b) => {
+ const mA = mastery.elements?.[a[0]];
+ const mB = mastery.elements?.[b[0]];
+ const pctA = mA?.attempts > 0 ? mA.correct / mA.attempts : 0;
+ const pctB = mB?.attempts > 0 ? mB.correct / mB.attempts : 0;
+ return pctA - pctB;
+ });
+
+ const questions = sorted.slice(0, 15).sort(() => Math.random() - 0.5).map(([symbol, info]) => {
+ const askSymbol = Math.random() > 0.5;
+ return askSymbol
+ ? { prompt: info.name, expected: symbol, element: symbol, label: 'What symbol?' }
+ : { prompt: `${symbol} (${info.atomicNumber})`, expected: info.name, element: symbol, label: 'What element?' };
+ });
+
+ const [idx, setIdx] = useState(0);
+ const [answer, setAnswer] = useState('');
+ const [showResult, setShowResult] = useState(null);
+ const [results, setResults] = useState([]);
+ const [startTime] = useState(Date.now());
+ const inputRef = useRef(null);
+
+ useEffect(() => { inputRef.current?.focus(); }, [idx]);
+
+ if (idx >= questions.length) {
+ const correct = results.filter(r => r.correct).length;
+ const pct = Math.round((correct / results.length) * 100);
+ const scoreColor = pct >= 80 ? 'text-port-success' : pct >= 50 ? 'text-port-warning' : 'text-port-error';
+
+ return (
+ <div className="space-y-6 max-w-2xl">
+ <div className="flex items-center gap-3">
+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors">
+ <ChevronLeft size={20} />
+ </button>
+ <h2 className="text-xl font-bold text-white">Element Flash Complete</h2>
+ </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>
+ </div>
+ {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">Missed</h3>
+ <div className="grid grid-cols-2 gap-2">
+ {results.filter(r => !r.correct).map((r, i) => (
+ <div key={i} className="text-xs bg-port-bg rounded p-2">
+ <span className="text-port-error">{r.answered || '?'}</span>
+ <span className="text-gray-500 mx-1">&rarr;</span>
+ <span className="text-port-success">{r.expected}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ <button
+ onClick={() => {
+ submitMemoryPractice(item.id, {
+ mode: 'element-flash', chunkId: null,
+ results: results.map(r => ({ correct: r.correct, element: r.element, expected: r.expected, answered: r.answered })),
+ totalMs: Date.now() - startTime,
+ }).then(r => onComplete(r?.mastery)).catch(() => onComplete(null));
+ }}
+ className="w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ >
+ Save & Return
+ </button>
+ </div>
+ );
+ }
+
+ const q = questions[idx];
+
+ function check(skipped = false) {
+ const isCorrect = !skipped && answer.trim().toLowerCase() === q.expected.toLowerCase();
+ setResults(prev => [...prev, { correct: isCorrect, expected: q.expected, answered: answer.trim(), element: q.element }]);
+ setShowResult(isCorrect ? 'correct' : 'wrong');
+ }
+
+ function next() {
+ setIdx(prev => prev + 1);
+ setAnswer('');
+ setShowResult(null);
+ }
+
+ return (
+ <div className="space-y-6 max-w-2xl">
+ <div className="flex items-center gap-3">
+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors">
+ <ChevronLeft size={20} />
+ </button>
+ <h2 className="text-lg font-bold text-white">Element Flash</h2>
+ <span className="text-gray-500 text-sm ml-auto">{idx + 1} / {questions.length}</span>
+ </div>
+
+ <div className="w-full h-1.5 bg-port-border rounded-full overflow-hidden">
+ <div className="h-full bg-emerald-500 rounded-full transition-all" style={{ width: `${((idx + 1) / questions.length) * 100}%` }} />
+ </div>
+
+ <div className="bg-port-card border border-port-border rounded-lg p-8 text-center">
+ <div className="text-3xl font-bold text-white mb-2">{q.prompt}</div>
+ <div className="text-gray-500 text-sm">{q.label}</div>
+
+ {showResult ? (
+ <div className={`mt-6 text-lg font-medium ${showResult === 'correct' ? 'text-port-success' : 'text-port-error'}`}>
+ {showResult === 'correct' ? 'Correct!' : `Wrong — answer: ${q.expected}`}
+ </div>
+ ) : (
+ <input
+ ref={inputRef}
+ type="text"
+ value={answer}
+ onChange={e => setAnswer(e.target.value)}
+ onKeyDown={e => { if (e.key === 'Enter') check(); }}
+ className="mt-6 w-48 bg-port-bg border border-port-border rounded-lg px-4 py-2.5 text-white text-center text-lg placeholder-gray-600 focus:border-port-accent focus:outline-none"
+ placeholder="..."
+ autoComplete="off"
+ />
+ )}
+ </div>
+
+ <div className="flex gap-3">
+ {showResult ? (
+ <button onClick={next} className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors">
+ Next
+ </button>
+ ) : (
+ <>
+ <button
+ onClick={() => check()}
+ 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"
+ >
+ <Check size={16} /> Check
+ </button>
+ <button
+ onClick={() => check(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} />
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// =============================================================================
+// FILL BLANK MODE (lyrics-specific)
+// =============================================================================
+
+function FillBlankMode({ item, onBack, onComplete }) {
+ const lines = (item.content?.lines || []).filter(l => l.elements?.length > 0);
+ const [idx, setIdx] = useState(0);
+ const [answer, setAnswer] = useState('');
+ const [showResult, setShowResult] = useState(null);
+ const [results, setResults] = useState([]);
+ const [startTime] = useState(Date.now());
+ const inputRef = useRef(null);
+
+ useEffect(() => { inputRef.current?.focus(); }, [idx]);
+
+ if (idx >= lines.length) {
+ const correct = results.filter(r => r.correct).length;
+ const pct = Math.round((correct / results.length) * 100);
+ const scoreColor = pct >= 80 ? 'text-port-success' : pct >= 50 ? 'text-port-warning' : 'text-port-error';
+
+ return (
+ <div className="space-y-6 max-w-2xl">
+ <div className="flex items-center gap-3">
+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors">
+ <ChevronLeft size={20} />
+ </button>
+ <h2 className="text-xl font-bold text-white">Fill the Lyrics Complete</h2>
+ </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} lines correct</div>
+ </div>
+ <button
+ onClick={() => {
+ submitMemoryPractice(item.id, {
+ mode: 'fill-blank', chunkId: null,
+ results: results.map(r => ({ correct: r.correct, expected: r.expected, answered: r.answered })),
+ totalMs: Date.now() - startTime,
+ }).then(r => onComplete(r?.mastery)).catch(() => onComplete(null));
+ }}
+ className="w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ >
+ Save & Return
+ </button>
+ </div>
+ );
+ }
+
+ const line = lines[idx];
+ const elementMap = item.content?.elementMap || {};
+
+ // Blank out element names
+ const words = line.text.split(/\s+/);
+ const blankedWords = [];
+ const display = words.map(w => {
+ const clean = w.toLowerCase().replace(/[,.\s]/g, '');
+ for (const [sym, info] of Object.entries(elementMap)) {
+ if (info.name.toLowerCase() === clean && line.elements?.includes(sym)) {
+ blankedWords.push(info.name);
+ return '________';
+ }
+ }
+ return w;
+ }).join(' ');
+
+ function check(skipped = false) {
+ const userWords = skipped ? [] : answer.split(',').map(w => w.trim().toLowerCase());
+ const expectedWords = blankedWords.map(w => w.toLowerCase());
+ const allCorrect = expectedWords.every((ew, i) => userWords[i] === ew);
+ setResults(prev => [...prev, {
+ correct: allCorrect,
+ expected: blankedWords.join(', '),
+ answered: skipped ? '' : answer,
+ }]);
+ setShowResult(allCorrect ? 'correct' : 'wrong');
+ }
+
+ function next() {
+ setIdx(prev => prev + 1);
+ setAnswer('');
+ setShowResult(null);
+ }
+
+ return (
+ <div className="space-y-6 max-w-2xl">
+ <div className="flex items-center gap-3">
+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors">
+ <ChevronLeft size={20} />
+ </button>
+ <h2 className="text-lg font-bold text-white">Fill the Lyrics</h2>
+ <span className="text-gray-500 text-sm ml-auto">{idx + 1} / {lines.length}</span>
+ </div>
+
+ <div className="w-full h-1.5 bg-port-border rounded-full overflow-hidden">
+ <div className="h-full bg-emerald-500 rounded-full transition-all" style={{ width: `${((idx + 1) / lines.length) * 100}%` }} />
+ </div>
+
+ <div className="bg-port-card border border-port-border rounded-lg p-6">
+ <div className="text-white text-lg leading-relaxed mb-4 font-mono">{display}</div>
+ <div className="text-gray-500 text-xs mb-2">
+ Element symbols in this line: {line.elements?.join(', ')}
+ </div>
+
+ {showResult ? (
+ <div className="space-y-2 mt-4">
+ <div className={`text-sm ${showResult === 'correct' ? 'text-port-success' : 'text-port-error'}`}>
+ {showResult === 'correct' ? 'Correct!' : `Expected: ${blankedWords.join(', ')}`}
+ </div>
+ <div className="text-sm text-gray-400">{line.text}</div>
+ </div>
+ ) : (
+ <div className="mt-4">
+ <div className="text-gray-400 text-xs mb-1">Name the blanked elements (comma-separated):</div>
+ <input
+ ref={inputRef}
+ type="text"
+ value={answer}
+ onChange={e => setAnswer(e.target.value)}
+ onKeyDown={e => { if (e.key === 'Enter') check(); }}
+ placeholder={`${blankedWords.length} element${blankedWords.length > 1 ? 's' : ''}...`}
+ 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"
+ />
+ </div>
+ )}
+ </div>
+
+ <div className="flex gap-3">
+ {showResult ? (
+ <button onClick={next} className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors">
+ {idx + 1 < lines.length ? 'Next' : 'Finish'}
+ </button>
+ ) : (
+ <>
+ <button
+ onClick={() => check()}
+ 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"
+ >
+ <Check size={16} /> Check
+ </button>
+ <button
+ onClick={() => check(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} />
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/meatspace/post/MemoryBuilder.jsx b/client/src/components/meatspace/post/MemoryBuilder.jsx
new file mode 100644
index 0000000000..b83a297738
--- /dev/null
+++ b/client/src/components/meatspace/post/MemoryBuilder.jsx
@@ -0,0 +1,146 @@
+import { useState, useEffect } from 'react';
+import { Brain, ChevronLeft, Plus, Trash2, BookOpen, Zap, FlaskConical, Eye } from 'lucide-react';
+import { getMemoryItems, deleteMemoryItem } from '../../../services/api';
+import MemoryPractice from './MemoryPractice';
+import ElementsSong from './ElementsSong';
+
+export default function MemoryBuilder({ onBack }) {
+ const [items, setItems] = useState([]);
+ const [selectedItem, setSelectedItem] = useState(null);
+ const [view, setView] = useState('list'); // list, practice, elements
+
+ useEffect(() => {
+ loadItems();
+ }, []);
+
+ async function loadItems() {
+ const data = await getMemoryItems().catch(() => []);
+ setItems(data || []);
+ }
+
+ function handleSelect(item) {
+ setSelectedItem(item);
+ if (item.id === 'elements-song') {
+ setView('elements');
+ } else {
+ setView('practice');
+ }
+ }
+
+ async function handleDelete(id) {
+ await deleteMemoryItem(id);
+ setItems(prev => prev.filter(i => i.id !== id));
+ }
+
+ function handlePracticeComplete() {
+ loadItems();
+ setView('list');
+ setSelectedItem(null);
+ }
+
+ if (view === 'elements' && selectedItem) {
+ return (
+ <ElementsSong
+ item={selectedItem}
+ onBack={() => { setView('list'); setSelectedItem(null); loadItems(); }}
+ />
+ );
+ }
+
+ if (view === 'practice' && selectedItem) {
+ return (
+ <MemoryPractice
+ item={selectedItem}
+ onBack={() => { setView('list'); setSelectedItem(null); }}
+ onComplete={handlePracticeComplete}
+ />
+ );
+ }
+
+ return (
+ <div className="space-y-6 max-w-2xl">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-3">
+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors">
+ <ChevronLeft size={20} />
+ </button>
+ <Brain size={24} className="text-emerald-400" />
+ <h2 className="text-xl font-bold text-white">Memory Builder</h2>
+ </div>
+ </div>
+
+ <p className="text-gray-400 text-sm">
+ Train your memory with songs, poems, speeches, and sequences. Track mastery and practice weak spots.
+ </p>
+
+ {/* Memory Items */}
+ <div className="space-y-3">
+ {items.map(item => (
+ <div
+ key={item.id}
+ className="bg-port-card border border-port-border rounded-lg p-4 hover:border-port-accent/50 transition-colors"
+ >
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-3 flex-1 min-w-0">
+ <ItemIcon type={item.type} builtin={item.builtin} />
+ <div className="min-w-0">
+ <h3 className="text-white font-medium truncate">{item.title}</h3>
+ <div className="flex items-center gap-3 text-xs text-gray-500 mt-0.5">
+ <span>{item.type}</span>
+ <span>{item.content?.lines?.length || 0} lines</span>
+ {item.builtin && <span className="text-emerald-500">built-in</span>}
+ </div>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-3">
+ <MasteryBadge pct={item.mastery?.overallPct || 0} />
+ <button
+ onClick={() => handleSelect(item)}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ >
+ <BookOpen size={14} />
+ Practice
+ </button>
+ {!item.builtin && (
+ <button
+ onClick={() => handleDelete(item.id)}
+ className="p-1.5 text-gray-500 hover:text-port-error transition-colors"
+ >
+ <Trash2 size={14} />
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ ))}
+
+ {items.length === 0 && (
+ <div className="bg-port-card border border-port-border rounded-lg p-8 text-center">
+ <Brain size={32} className="text-gray-600 mx-auto mb-3" />
+ <p className="text-gray-500">No memory items yet. The Elements Song will be added automatically.</p>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function ItemIcon({ type, builtin }) {
+ if (builtin) return <FlaskConical size={20} className="text-emerald-400 shrink-0" />;
+ switch (type) {
+ case 'song': return <Zap size={20} className="text-purple-400 shrink-0" />;
+ case 'poem': return <BookOpen size={20} className="text-blue-400 shrink-0" />;
+ case 'speech': return <Eye size={20} className="text-amber-400 shrink-0" />;
+ default: return <Brain size={20} className="text-gray-400 shrink-0" />;
+ }
+}
+
+function MasteryBadge({ pct }) {
+ const color = pct >= 80 ? 'text-port-success' : pct >= 40 ? 'text-port-warning' : 'text-gray-500';
+ return (
+ <div className={`text-sm font-mono font-medium ${color}`}>
+ {pct}%
+ </div>
+ );
+}
diff --git a/client/src/components/meatspace/post/MemoryPractice.jsx b/client/src/components/meatspace/post/MemoryPractice.jsx
new file mode 100644
index 0000000000..b9790c92fc
--- /dev/null
+++ b/client/src/components/meatspace/post/MemoryPractice.jsx
@@ -0,0 +1,507 @@
+import { useState, useRef, useEffect } from 'react';
+import { ChevronLeft, Play, Check, X, SkipForward, RotateCcw } from 'lucide-react';
+import { submitMemoryPractice } from '../../../services/api';
+
+const MODES = [
+ { id: 'learn', label: 'Learn', desc: 'Progressive reveal — read and absorb line by line' },
+ { id: 'fill-blank', label: 'Fill in the Blank', desc: 'Fill missing words in partially shown lines' },
+ { id: 'sequence', label: 'Sequence Recall', desc: 'Given a line, type what comes next' },
+ { id: 'speed-run', label: 'Speed Run', desc: 'Recite the full sequence as fast as possible' },
+];
+
+export default function MemoryPractice({ item, onBack, onComplete }) {
+ const [mode, setMode] = useState(null);
+ const [results, setResults] = useState([]);
+ const [currentIdx, setCurrentIdx] = useState(0);
+ const [answer, setAnswer] = useState('');
+ const [showResult, setShowResult] = useState(null); // null | 'correct' | 'wrong'
+ const [done, setDone] = useState(false);
+ const [startTime] = useState(Date.now());
+ const inputRef = useRef(null);
+
+ const lines = item.content?.lines || [];
+
+ useEffect(() => {
+ if (mode && inputRef.current) inputRef.current.focus();
+ }, [mode, currentIdx]);
+
+ if (!mode) {
+ return (
+ <div className="space-y-6 max-w-2xl">
+ <div className="flex items-center gap-3">
+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors">
+ <ChevronLeft size={20} />
+ </button>
+ <h2 className="text-xl font-bold text-white">{item.title}</h2>
+ </div>
+
+ <p className="text-gray-400 text-sm">Choose a practice mode:</p>
+
+ <div className="space-y-3">
+ {MODES.map(m => (
+ <button
+ key={m.id}
+ onClick={() => setMode(m.id)}
+ className="w-full bg-port-card border border-port-border rounded-lg p-4 text-left hover:border-port-accent/50 transition-colors"
+ >
+ <div className="text-white font-medium">{m.label}</div>
+ <div className="text-gray-500 text-sm mt-1">{m.desc}</div>
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+ }
+
+ if (done) {
+ 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';
+
+ return (
+ <div className="space-y-6 max-w-2xl">
+ <div className="flex items-center gap-3">
+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors">
+ <ChevronLeft size={20} />
+ </button>
+ <h2 className="text-xl font-bold text-white">Practice Complete</h2>
+ </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>
+ <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 && (
+ <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">
+ {results.filter(r => !r.correct).map((r, i) => (
+ <div key={i} className="text-sm">
+ <div className="text-port-error">Your answer: {r.answered || '(skipped)'}</div>
+ <div className="text-port-success">Expected: {r.expected}</div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ <div className="flex gap-3">
+ <button
+ onClick={() => { setMode(null); setResults([]); setCurrentIdx(0); setDone(false); setShowResult(null); }}
+ className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-port-card border border-port-border rounded-lg text-gray-300 hover:text-white transition-colors"
+ >
+ <RotateCcw size={16} />
+ Try Again
+ </button>
+ <button
+ onClick={onBack}
+ className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ >
+ Done
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ // LEARN mode — progressive reveal
+ if (mode === 'learn') {
+ return (
+ <div className="space-y-6 max-w-2xl">
+ <div className="flex items-center gap-3">
+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors">
+ <ChevronLeft size={20} />
+ </button>
+ <h2 className="text-lg font-bold text-white">Learn — {item.title}</h2>
+ <span className="text-gray-500 text-sm ml-auto">{currentIdx + 1} / {lines.length}</span>
+ </div>
+
+ <ProgressBar current={currentIdx + 1} total={lines.length} />
+
+ <div className="bg-port-card border border-port-border rounded-lg p-6">
+ <div className="space-y-2">
+ {lines.slice(0, currentIdx + 1).map((line, i) => (
+ <div
+ key={i}
+ className={`text-sm leading-relaxed transition-all ${
+ i === currentIdx ? 'text-white font-medium text-base' : 'text-gray-500'
+ }`}
+ >
+ {line.text}
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="flex gap-3">
+ {currentIdx > 0 && (
+ <button
+ onClick={() => setCurrentIdx(prev => prev - 1)}
+ className="px-4 py-2.5 bg-port-card border border-port-border rounded-lg text-gray-300 hover:text-white transition-colors"
+ >
+ Previous
+ </button>
+ )}
+ {currentIdx < lines.length - 1 ? (
+ <button
+ onClick={() => setCurrentIdx(prev => prev + 1)}
+ className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ >
+ Next Line
+ </button>
+ ) : (
+ <button
+ onClick={() => { setDone(true); setResults([{ correct: true, expected: 'learn mode', answered: 'learn mode' }]); savePractice('learn', [{ correct: true }]); }}
+ 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} />
+ Complete
+ </button>
+ )}
+ </div>
+ </div>
+ );
+ }
+
+ // SEQUENCE mode — given a line, type the next one
+ if (mode === 'sequence') {
+ const promptLine = lines[currentIdx];
+ const expectedLine = lines[currentIdx + 1];
+
+ if (!expectedLine) {
+ finishSequence();
+ return null;
+ }
+
+ return (
+ <div className="space-y-6 max-w-2xl">
+ <div className="flex items-center gap-3">
+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors">
+ <ChevronLeft size={20} />
+ </button>
+ <h2 className="text-lg font-bold text-white">Sequence — {item.title}</h2>
+ <span className="text-gray-500 text-sm ml-auto">{currentIdx + 1} / {lines.length - 1}</span>
+ </div>
+
+ <ProgressBar current={currentIdx + 1} total={lines.length - 1} />
+
+ <div className="bg-port-card border border-port-border rounded-lg p-6">
+ <div className="text-gray-400 text-xs mb-2 uppercase tracking-wide">Current line:</div>
+ <div className="text-white text-lg leading-relaxed mb-6">{promptLine.text}</div>
+
+ <div className="text-gray-400 text-xs mb-2 uppercase tracking-wide">What comes next?</div>
+ {showResult ? (
+ <div className="space-y-2">
+ <div className={`text-sm p-3 rounded ${showResult === 'correct' ? 'bg-port-success/10 text-port-success' : 'bg-port-error/10 text-port-error'}`}>
+ {showResult === 'correct' ? 'Correct!' : `Your answer: ${answer}`}
+ </div>
+ {showResult === 'wrong' && (
+ <div className="text-sm p-3 rounded bg-port-success/10 text-port-success">
+ Expected: {expectedLine.text}
+ </div>
+ )}
+ </div>
+ ) : (
+ <textarea
+ ref={inputRef}
+ value={answer}
+ onChange={e => setAnswer(e.target.value)}
+ onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); checkSequenceAnswer(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}
+ />
+ )}
+ </div>
+
+ <div className="flex gap-3">
+ {showResult ? (
+ <button
+ onClick={nextSequenceQuestion}
+ className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ >
+ {currentIdx + 1 < lines.length - 1 ? 'Next' : 'Finish'}
+ </button>
+ ) : (
+ <>
+ <button
+ onClick={() => checkSequenceAnswer(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"
+ >
+ <Check size={16} />
+ Check
+ </button>
+ <button
+ onClick={() => { setAnswer(''); checkSequenceAnswer(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} />
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+ );
+ }
+
+ // FILL-IN-THE-BLANK mode
+ if (mode === 'fill-blank') {
+ const line = lines[currentIdx];
+ const words = line?.text.split(/\s+/) || [];
+ // Blank out ~40% of words
+ const [blanks] = useState(() => {
+ const blankSet = new Set();
+ const count = Math.max(1, Math.floor(words.length * 0.4));
+ while (blankSet.size < count && blankSet.size < words.length) {
+ blankSet.add(Math.floor(Math.random() * words.length));
+ }
+ return blankSet;
+ });
+
+ const blankWords = [...blanks].sort((a, b) => a - b).map(i => words[i]?.replace(/[,.]$/, ''));
+ const displayText = words.map((w, i) => blanks.has(i) ? '____' : w).join(' ');
+
+ return (
+ <div className="space-y-6 max-w-2xl">
+ <div className="flex items-center gap-3">
+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors">
+ <ChevronLeft size={20} />
+ </button>
+ <h2 className="text-lg font-bold text-white">Fill Blank — {item.title}</h2>
+ <span className="text-gray-500 text-sm ml-auto">{currentIdx + 1} / {lines.length}</span>
+ </div>
+
+ <ProgressBar current={currentIdx + 1} total={lines.length} />
+
+ <div className="bg-port-card border border-port-border rounded-lg p-6">
+ <div className="text-white text-lg leading-relaxed mb-4 font-mono">{displayText}</div>
+
+ {showResult ? (
+ <div className="space-y-2">
+ <div className="text-sm text-gray-400">Full line:</div>
+ <div className="text-port-success text-sm">{line.text}</div>
+ </div>
+ ) : (
+ <div>
+ <div className="text-gray-400 text-xs mb-2">Fill the blanks (comma-separated):</div>
+ <input
+ ref={inputRef}
+ type="text"
+ value={answer}
+ onChange={e => setAnswer(e.target.value)}
+ onKeyDown={e => { if (e.key === 'Enter') checkFillBlank(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"
+ />
+ </div>
+ )}
+ </div>
+
+ <div className="flex gap-3">
+ {showResult ? (
+ <button
+ onClick={nextFillBlank}
+ className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ >
+ {currentIdx + 1 < lines.length ? 'Next' : 'Finish'}
+ </button>
+ ) : (
+ <>
+ <button
+ onClick={() => checkFillBlank(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"
+ >
+ <Check size={16} />
+ Check
+ </button>
+ <button
+ onClick={() => { setAnswer(''); checkFillBlank(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} />
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+ );
+ }
+
+ // SPEED RUN mode — show all lines, check how many you can recite
+ if (mode === 'speed-run') {
+ return (
+ <div className="space-y-6 max-w-2xl">
+ <div className="flex items-center gap-3">
+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors">
+ <ChevronLeft size={20} />
+ </button>
+ <h2 className="text-lg font-bold text-white">Speed Run — {item.title}</h2>
+ </div>
+
+ <div className="bg-port-card border border-port-border rounded-lg p-6">
+ <p className="text-gray-400 text-sm mb-4">
+ Try to recite the full text from memory. Tap each line to reveal it and check yourself.
+ </p>
+ <div className="space-y-1">
+ {lines.map((line, i) => (
+ <SpeedRunLine key={i} line={line} index={i} onResult={(correct) => {
+ setResults(prev => [...prev, { correct, expected: line.text, answered: correct ? line.text : '(wrong)' }]);
+ }} />
+ ))}
+ </div>
+ </div>
+
+ {results.length === lines.length && (
+ <button
+ onClick={() => { savePractice('speed-run', results); setDone(true); }}
+ className="w-full 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} />
+ Finish ({results.filter(r => r.correct).length}/{results.length} correct)
+ </button>
+ )}
+ </div>
+ );
+ }
+
+ return null;
+
+ // --- 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 nextSequenceQuestion() {
+ if (currentIdx + 1 >= lines.length - 1) {
+ finishSequence();
+ } else {
+ setCurrentIdx(prev => prev + 1);
+ setAnswer('');
+ setShowResult(null);
+ }
+ }
+
+ function finishSequence() {
+ savePractice('sequence', results);
+ 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 nextFillBlank() {
+ if (currentIdx + 1 >= lines.length) {
+ savePractice('fill-blank', results);
+ setDone(true);
+ } else {
+ setCurrentIdx(prev => prev + 1);
+ setAnswer('');
+ setShowResult(null);
+ }
+ }
+
+ async function savePractice(practiceMode, practiceResults) {
+ const chunkId = findChunkForLine(item, currentIdx);
+ await submitMemoryPractice(item.id, {
+ mode: practiceMode,
+ chunkId,
+ results: practiceResults.map(r => ({
+ correct: r.correct,
+ word: r.expected?.split(' ')[0],
+ element: r.element || null,
+ expected: r.expected,
+ answered: r.answered,
+ })),
+ totalMs: Date.now() - startTime,
+ }).catch(() => {});
+ }
+}
+
+function SpeedRunLine({ line, index, onResult }) {
+ const [revealed, setRevealed] = useState(false);
+ const [marked, setMarked] = useState(null);
+
+ function reveal() {
+ if (!revealed) setRevealed(true);
+ }
+
+ function mark(correct) {
+ setMarked(correct);
+ onResult(correct);
+ }
+
+ return (
+ <div className="flex items-center gap-2">
+ <span className="text-gray-600 text-xs w-6 text-right shrink-0">{index + 1}</span>
+ {!revealed ? (
+ <button
+ onClick={reveal}
+ className="flex-1 text-left px-3 py-1.5 bg-port-bg border border-port-border rounded text-gray-600 hover:text-gray-400 hover:border-port-accent/30 transition-colors text-sm"
+ >
+ Tap to reveal...
+ </button>
+ ) : (
+ <div className="flex-1 flex items-center gap-2">
+ <span className={`text-sm flex-1 ${marked === true ? 'text-port-success' : marked === false ? 'text-port-error' : 'text-white'}`}>
+ {line.text}
+ </span>
+ {marked === null && (
+ <div className="flex gap-1 shrink-0">
+ <button onClick={() => mark(true)} className="p-1 text-port-success hover:bg-port-success/10 rounded"><Check size={14} /></button>
+ <button onClick={() => mark(false)} className="p-1 text-port-error hover:bg-port-error/10 rounded"><X size={14} /></button>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function ProgressBar({ current, total }) {
+ const pct = Math.round((current / total) * 100);
+ return (
+ <div className="w-full h-1.5 bg-port-border rounded-full overflow-hidden">
+ <div className="h-full bg-port-accent rounded-full transition-all" style={{ width: `${pct}%` }} />
+ </div>
+ );
+}
+
+function fuzzyMatch(input, expected) {
+ const normalize = s => s.toLowerCase().replace(/[,.\-!?'"]/g, '').replace(/\s+/g, ' ').trim();
+ const a = normalize(input);
+ const b = normalize(expected);
+ if (a === b) return true;
+ // Allow 80% word match
+ const aWords = a.split(' ');
+ const bWords = b.split(' ');
+ const matches = bWords.filter(w => aWords.includes(w)).length;
+ return matches / bWords.length >= 0.8;
+}
+
+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;
+}
diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsx
index 824f1fd28e..811e622055 100644
--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx
+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react';
-import { Zap, History, Settings, Play, Brain } from 'lucide-react';
+import { Zap, History, Settings, Play, Brain, BookOpen } from 'lucide-react';
import { getProviders } from '../../../services/api';
const DRILL_LABELS = {
@@ -12,10 +12,13 @@ const DRILL_LABELS = {
'story-recall': 'Story Recall',
'verbal-fluency': 'Verbal Fluency',
'wit-comeback': 'Wit & Comeback',
- 'pun-wordplay': 'Pun & Wordplay'
+ 'pun-wordplay': 'Pun & Wordplay',
+ 'memory-fill-blank': 'Memory Fill Blank',
+ 'memory-sequence': 'Memory Sequence',
+ 'memory-element-flash': 'Element Flash'
};
-export default function PostSessionLauncher({ config, recentSessions, onStart, onViewHistory, onViewConfig }) {
+export default function PostSessionLauncher({ config, recentSessions, onStart, onViewHistory, onViewConfig, onViewMemory }) {
const [tags, setTags] = useState({ sleep: '', caffeine: '', stress: '' });
const [providers, setProviders] = useState([]);
@@ -84,6 +87,13 @@ export default function PostSessionLauncher({ config, recentSessions, onStart, o
<h2 className="text-xl font-bold text-white">Power On Self Test</h2>
</div>
<div className="flex gap-2">
+ <button
+ onClick={onViewMemory}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-400 hover:text-white bg-port-card border border-port-border rounded-lg transition-colors"
+ >
+ <BookOpen size={14} />
+ Memory
+ </button>
<button
onClick={onViewHistory}
className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-400 hover:text-white bg-port-card border border-port-border rounded-lg transition-colors"
diff --git a/client/src/components/meatspace/post/constants.js b/client/src/components/meatspace/post/constants.js
index 9a63f3c7bd..d6314f8b9b 100644
--- a/client/src/components/meatspace/post/constants.js
+++ b/client/src/components/meatspace/post/constants.js
@@ -1 +1,2 @@
export const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay'];
+export const MEMORY_DRILL_TYPES = ['memory-fill-blank', 'memory-sequence', 'memory-element-flash'];
diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsx
index 8f5bfa411e..e8d791b44a 100644
--- a/client/src/components/meatspace/tabs/PostTab.jsx
+++ b/client/src/components/meatspace/tabs/PostTab.jsx
@@ -7,6 +7,7 @@ import PostLlmDrillRunner from '../post/PostLlmDrillRunner';
import PostSessionResults from '../post/PostSessionResults';
import PostHistory from '../post/PostHistory';
import PostDrillConfig from '../post/PostDrillConfig';
+import MemoryBuilder from '../post/MemoryBuilder';
import { LLM_DRILL_TYPES } from '../post/constants';
export default function PostTab() {
@@ -53,6 +54,10 @@ export default function PostTab() {
setView('config');
}
+ function handleViewMemory() {
+ setView('memory');
+ }
+
function handleConfigSaved(newConfig) {
setConfig(newConfig);
setView('launcher');
@@ -121,6 +126,12 @@ export default function PostTab() {
onBack={() => setView('launcher')}
/>
);
+ case 'memory':
+ return (
+ <MemoryBuilder
+ onBack={() => setView('launcher')}
+ />
+ );
default:
return (
<PostSessionLauncher
@@ -129,6 +140,7 @@ export default function PostTab() {
onStart={handleStart}
onViewHistory={handleViewHistory}
onViewConfig={handleViewConfig}
+ onViewMemory={handleViewMemory}
/>
);
}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index b98b240961..842ff9f41e 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1513,6 +1513,30 @@ export const scorePostLlmDrill = (type, drillData, responses, timeLimitMs, provi
body: JSON.stringify({ type, drillData, responses, timeLimitMs, ...(providerId && { providerId }), ...(model && { model }) })
});
+// MeatSpace - POST Memory Builder
+export const getMemoryItems = () => request('/meatspace/post/memory-items');
+export const getMemoryItem = (id) => request(`/meatspace/post/memory-items/${id}`);
+export const createMemoryItem = (data) => request('/meatspace/post/memory-items', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+export const updateMemoryItem = (id, data) => request(`/meatspace/post/memory-items/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify(data)
+});
+export const deleteMemoryItem = (id) => request(`/meatspace/post/memory-items/${id}`, {
+ method: 'DELETE'
+});
+export const submitMemoryPractice = (id, data) => request(`/meatspace/post/memory-items/${id}/practice`, {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+export const getMemoryMastery = (id) => request(`/meatspace/post/memory-items/${id}/mastery`);
+export const generateMemoryDrill = (data) => request('/meatspace/post/memory-drill', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+
// Life Calendar
export const getLifeCalendar = () => request('/meatspace/calendar');
export const getActivities = () => request('/meatspace/activities');
diff --git a/server/lib/postValidation.js b/server/lib/postValidation.js
index c51d804b8e..19abf7bc7d 100644
--- a/server/lib/postValidation.js
+++ b/server/lib/postValidation.js
@@ -31,7 +31,8 @@ const llmResponseSchema = z.object({
// Drill type configuration
const MATH_DRILL_TYPES = ['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation'];
const LLM_DRILL_TYPES = ['word-association', 'story-recall', 'verbal-fluency', 'wit-comeback', 'pun-wordplay'];
-const DRILL_TYPES = [...MATH_DRILL_TYPES, ...LLM_DRILL_TYPES];
+const MEMORY_DRILL_TYPES = ['memory-fill-blank', 'memory-sequence', 'memory-element-flash'];
+const DRILL_TYPES = [...MATH_DRILL_TYPES, ...LLM_DRILL_TYPES, ...MEMORY_DRILL_TYPES];
const drillTypeConfigSchema = z.object({
enabled: z.boolean().optional(),
@@ -121,4 +122,66 @@ export const postLlmScoreRequestSchema = z.object({
model: z.string().optional()
});
-export { LLM_DRILL_TYPES, MATH_DRILL_TYPES };
+// =============================================================================
+// MEMORY BUILDER VALIDATION
+// =============================================================================
+
+const memoryLineSchema = z.object({
+ text: z.string().min(1),
+ elements: z.array(z.string()).optional(),
+});
+
+const memoryChunkSchema = z.object({
+ id: z.string(),
+ lineRange: z.array(z.number().int().min(0)).length(2),
+ label: z.string(),
+});
+
+export const memoryItemCreateSchema = z.object({
+ title: z.string().min(1).max(200),
+ type: z.enum(['song', 'poem', 'speech', 'sequence', 'text']).optional().default('text'),
+ lines: z.array(z.union([z.string(), memoryLineSchema])).min(1),
+ chunks: z.array(memoryChunkSchema).optional(),
+});
+
+export const memoryItemUpdateSchema = z.object({
+ title: z.string().min(1).max(200).optional(),
+ type: z.enum(['song', 'poem', 'speech', 'sequence', 'text']).optional(),
+ lines: z.array(z.union([z.string(), memoryLineSchema])).optional(),
+ chunks: z.array(memoryChunkSchema).optional(),
+ mastery: z.object({
+ overallPct: z.number().min(0).max(100).optional(),
+ chunks: z.record(z.object({
+ correct: z.number().int().min(0),
+ attempts: z.number().int().min(0),
+ lastPracticed: z.string().nullable().optional(),
+ })).optional(),
+ elements: z.record(z.object({
+ correct: z.number().int().min(0),
+ attempts: z.number().int().min(0),
+ })).optional(),
+ }).optional(),
+});
+
+const practiceResultSchema = z.object({
+ correct: z.boolean(),
+ word: z.string().optional(),
+ element: z.string().nullable().optional(),
+ expected: z.string().optional(),
+ answered: z.string().optional(),
+});
+
+export const memoryPracticeSchema = z.object({
+ mode: z.enum(['fill-blank', 'sequence', 'element-flash', 'learn', 'speed-run']),
+ chunkId: z.string().nullable().optional(),
+ results: z.array(practiceResultSchema).min(1),
+ totalMs: z.number().min(0).optional(),
+});
+
+export const memoryDrillRequestSchema = z.object({
+ mode: z.enum(['fill-blank', 'sequence', 'element-flash']).optional().default('fill-blank'),
+ memoryItemId: z.string().optional(),
+ count: z.number().int().min(1).max(30).optional().default(5),
+});
+
+export { LLM_DRILL_TYPES, MATH_DRILL_TYPES, MEMORY_DRILL_TYPES };
diff --git a/server/routes/meatspace.js b/server/routes/meatspace.js
index 1b9ce3da8a..c5eab8bcaf 100644
--- a/server/routes/meatspace.js
+++ b/server/routes/meatspace.js
@@ -22,12 +22,18 @@ import {
postConfigUpdateSchema,
postDrillRequestSchema,
postLlmScoreRequestSchema,
+ memoryItemCreateSchema,
+ memoryItemUpdateSchema,
+ memoryPracticeSchema,
+ memoryDrillRequestSchema,
LLM_DRILL_TYPES,
+ MEMORY_DRILL_TYPES,
} from '../lib/postValidation.js';
import * as meatspaceService from '../services/meatspace.js';
import * as alcoholService from '../services/meatspaceAlcohol.js';
import * as healthService from '../services/meatspaceHealth.js';
import * as postService from '../services/meatspacePost.js';
+import * as memoryService from '../services/meatspacePostMemory.js';
import { generateLlmDrill, scoreLlmDrill } from '../services/meatspacePostLlm.js';
import * as calendarService from '../services/meatspaceCalendar.js';
@@ -442,6 +448,15 @@ router.post('/post/drill', asyncHandler(async (req, res) => {
return res.json(drill);
}
+ if (MEMORY_DRILL_TYPES.includes(data.type)) {
+ const mode = data.type.replace('memory-', '');
+ const drill = await memoryService.generateMemoryDrill({ mode, count: data.config?.count, memoryItemId: data.config?.memoryItemId });
+ if (!drill) {
+ throw new ServerError('Failed to generate memory drill', { status: 500, code: 'MEMORY_DRILL_FAILED' });
+ }
+ return res.json(drill);
+ }
+
const drill = postService.generateDrill(data.type, data.config);
if (!drill) {
throw new ServerError('Unknown drill type', { status: 400, code: 'INVALID_DRILL_TYPE' });
@@ -462,6 +477,92 @@ router.post('/post/score-llm', asyncHandler(async (req, res) => {
res.json(result);
}));
+// =============================================================================
+// POST - Memory Builder
+// =============================================================================
+
+/**
+ * GET /api/meatspace/post/memory-items
+ * List all memory items (includes built-in Elements Song)
+ */
+router.get('/post/memory-items', asyncHandler(async (req, res) => {
+ const items = await memoryService.getMemoryItems();
+ res.json(items);
+}));
+
+/**
+ * GET /api/meatspace/post/memory-items/:id
+ * Get a single memory item
+ */
+router.get('/post/memory-items/:id', asyncHandler(async (req, res) => {
+ const item = await memoryService.getMemoryItem(req.params.id);
+ if (!item) throw new ServerError('Memory item not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(item);
+}));
+
+/**
+ * POST /api/meatspace/post/memory-items
+ * Create a custom memory item
+ */
+router.post('/post/memory-items', asyncHandler(async (req, res) => {
+ const data = validateRequest(memoryItemCreateSchema, req.body);
+ const item = await memoryService.createMemoryItem(data);
+ res.status(201).json(item);
+}));
+
+/**
+ * PUT /api/meatspace/post/memory-items/:id
+ * Update a memory item (built-in items: mastery only)
+ */
+router.put('/post/memory-items/:id', asyncHandler(async (req, res) => {
+ const data = validateRequest(memoryItemUpdateSchema, req.body);
+ const item = await memoryService.updateMemoryItem(req.params.id, data);
+ if (!item) throw new ServerError('Memory item not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(item);
+}));
+
+/**
+ * DELETE /api/meatspace/post/memory-items/:id
+ * Delete a custom memory item (built-in items cannot be deleted)
+ */
+router.delete('/post/memory-items/:id', asyncHandler(async (req, res) => {
+ const removed = await memoryService.deleteMemoryItem(req.params.id);
+ if (!removed) throw new ServerError('Cannot delete item (not found or built-in)', { status: 400, code: 'DELETE_FAILED' });
+ res.json(removed);
+}));
+
+/**
+ * POST /api/meatspace/post/memory-items/:id/practice
+ * Submit practice results and update mastery
+ */
+router.post('/post/memory-items/:id/practice', asyncHandler(async (req, res) => {
+ const data = validateRequest(memoryPracticeSchema, req.body);
+ const result = await memoryService.submitPractice(req.params.id, data);
+ if (!result) throw new ServerError('Memory item not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(result);
+}));
+
+/**
+ * GET /api/meatspace/post/memory-items/:id/mastery
+ * Get mastery breakdown for a memory item
+ */
+router.get('/post/memory-items/:id/mastery', asyncHandler(async (req, res) => {
+ const mastery = await memoryService.getMastery(req.params.id);
+ if (!mastery) throw new ServerError('Memory item not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(mastery);
+}));
+
+/**
+ * POST /api/meatspace/post/memory-drill
+ * Generate a memory drill for a POST session
+ */
+router.post('/post/memory-drill', asyncHandler(async (req, res) => {
+ const data = validateRequest(memoryDrillRequestSchema, req.body);
+ const drill = await memoryService.generateMemoryDrill(data);
+ if (!drill) throw new ServerError('No memory items available', { status: 400, code: 'NO_MEMORY_ITEMS' });
+ res.json(drill);
+}));
+
// ============================================================
// Life Calendar
// ============================================================
diff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.js
new file mode 100644
index 0000000000..39bdd8bf1d
--- /dev/null
+++ b/server/services/meatspacePostMemory.js
@@ -0,0 +1,508 @@
+/**
+ * MeatSpace POST - Memory Builder Service
+ *
+ * CRUD and practice tracking for memory items (songs, poems, speeches, sequences).
+ * Built-in content: Tom Lehrer's "The Elements" song.
+ */
+
+import { writeFile } from 'fs/promises';
+import { join } from 'path';
+import { randomUUID } from 'crypto';
+import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
+
+const MEATSPACE_DIR = PATHS.meatspace;
+const MEMORY_ITEMS_FILE = join(MEATSPACE_DIR, 'post-memory-items.json');
+const TRAINING_LOG_FILE = join(MEATSPACE_DIR, 'post-training-log.json');
+
+// =============================================================================
+// TOM LEHRER'S ELEMENTS SONG — BUILT-IN CONTENT
+// =============================================================================
+
+const ELEMENTS_SONG = {
+ id: 'elements-song',
+ title: "The Elements (Tom Lehrer)",
+ type: 'song',
+ builtin: true,
+ content: {
+ lines: [
+ { text: "There's antimony, arsenic, aluminum, selenium,", elements: ["Sb", "As", "Al", "Se"] },
+ { text: "And hydrogen and oxygen and nitrogen and rhenium,", elements: ["H", "O", "N", "Re"] },
+ { text: "And nickel, neodymium, neptunium, germanium,", elements: ["Ni", "Nd", "Np", "Ge"] },
+ { text: "And iron, americium, ruthenium, uranium,", elements: ["Fe", "Am", "Ru", "U"] },
+ { text: "Europium, zirconium, lutetium, vanadium,", elements: ["Eu", "Zr", "Lu", "V"] },
+ { text: "And lanthanum and osmium and astatine and radium,", elements: ["La", "Os", "At", "Ra"] },
+ { text: "And gold and protactinium and indium and gallium,", elements: ["Au", "Pa", "In", "Ga"] },
+ { text: "And iodine and thorium and thulium and thallium.", elements: ["I", "Th", "Tm", "Tl"] },
+ { text: "There's yttrium, ytterbium, actinium, rubidium,", elements: ["Y", "Yb", "Ac", "Rb"] },
+ { text: "And boron, gadolinium, niobium, iridium,", elements: ["B", "Gd", "Nb", "Ir"] },
+ { text: "And strontium and silicon and silver and samarium,", elements: ["Sr", "Si", "Ag", "Sm"] },
+ { text: "And bismuth, bromine, lithium, beryllium, and barium.", elements: ["Bi", "Br", "Li", "Be", "Ba"] },
+ { text: "There's holmium and helium and hafnium and erbium,", elements: ["Ho", "He", "Hf", "Er"] },
+ { text: "And phosphorus and francium and fluorine and terbium,", elements: ["P", "Fr", "F", "Tb"] },
+ { text: "And manganese and mercury, molybdenum, magnesium,", elements: ["Mn", "Hg", "Mo", "Mg"] },
+ { text: "Dysprosium and scandium and cerium and cesium.", elements: ["Dy", "Sc", "Ce", "Cs"] },
+ { text: "And lead, praseodymium, and platinum, plutonium,", elements: ["Pb", "Pr", "Pt", "Pu"] },
+ { text: "Palladium, promethium, potassium, polonium,", elements: ["Pd", "Pm", "K", "Po"] },
+ { text: "And tantalum, technetium, titanium, tellurium,", elements: ["Ta", "Tc", "Ti", "Te"] },
+ { text: "And cadmium and calcium and chromium and curium.", elements: ["Cd", "Ca", "Cr", "Cm"] },
+ { text: "There's sulfur, californium, and fermium, berkelium,", elements: ["S", "Cf", "Fm", "Bk"] },
+ { text: "And also mendelevium, einsteinium, nobelium,", elements: ["Md", "Es", "No"] },
+ { text: "And argon, krypton, neon, radon, xenon, zinc, and rhodium,", elements: ["Ar", "Kr", "Ne", "Rn", "Xe", "Zn", "Rh"] },
+ { text: "And chlorine, carbon, cobalt, copper, tungsten, tin, and sodium.", elements: ["Cl", "C", "Co", "Cu", "W", "Sn", "Na"] },
+ { text: "These are the only ones of which the news has come to Harvard,", elements: [] },
+ { text: "And there may be many others, but they haven't been discovered.", elements: [] },
+ ],
+ chunks: [
+ { id: "verse-1", lineRange: [0, 7], label: "Verse 1" },
+ { id: "verse-2", lineRange: [8, 11], label: "Verse 2" },
+ { id: "verse-3", lineRange: [12, 15], label: "Verse 3" },
+ { id: "verse-4", lineRange: [16, 19], label: "Verse 4" },
+ { id: "verse-5", lineRange: [20, 23], label: "Verse 5" },
+ { id: "coda", lineRange: [24, 25], label: "Coda" },
+ ],
+ // Element symbol → { name, atomicNumber } for the periodic table visualization
+ elementMap: {
+ H: { name: "Hydrogen", atomicNumber: 1 }, He: { name: "Helium", atomicNumber: 2 },
+ Li: { name: "Lithium", atomicNumber: 3 }, Be: { name: "Beryllium", atomicNumber: 4 },
+ B: { name: "Boron", atomicNumber: 5 }, C: { name: "Carbon", atomicNumber: 6 },
+ N: { name: "Nitrogen", atomicNumber: 7 }, O: { name: "Oxygen", atomicNumber: 8 },
+ F: { name: "Fluorine", atomicNumber: 9 }, Ne: { name: "Neon", atomicNumber: 10 },
+ Na: { name: "Sodium", atomicNumber: 11 }, Mg: { name: "Magnesium", atomicNumber: 12 },
+ Al: { name: "Aluminum", atomicNumber: 13 }, Si: { name: "Silicon", atomicNumber: 14 },
+ P: { name: "Phosphorus", atomicNumber: 15 }, S: { name: "Sulfur", atomicNumber: 16 },
+ Cl: { name: "Chlorine", atomicNumber: 17 }, Ar: { name: "Argon", atomicNumber: 18 },
+ K: { name: "Potassium", atomicNumber: 19 }, Ca: { name: "Calcium", atomicNumber: 20 },
+ Sc: { name: "Scandium", atomicNumber: 21 }, Ti: { name: "Titanium", atomicNumber: 22 },
+ V: { name: "Vanadium", atomicNumber: 23 }, Cr: { name: "Chromium", atomicNumber: 24 },
+ Mn: { name: "Manganese", atomicNumber: 25 }, Fe: { name: "Iron", atomicNumber: 26 },
+ Co: { name: "Cobalt", atomicNumber: 27 }, Ni: { name: "Nickel", atomicNumber: 28 },
+ Cu: { name: "Copper", atomicNumber: 29 }, Zn: { name: "Zinc", atomicNumber: 30 },
+ Ga: { name: "Gallium", atomicNumber: 31 }, Ge: { name: "Germanium", atomicNumber: 32 },
+ As: { name: "Arsenic", atomicNumber: 33 }, Se: { name: "Selenium", atomicNumber: 34 },
+ Br: { name: "Bromine", atomicNumber: 35 }, Kr: { name: "Krypton", atomicNumber: 36 },
+ Rb: { name: "Rubidium", atomicNumber: 37 }, Sr: { name: "Strontium", atomicNumber: 38 },
+ Y: { name: "Yttrium", atomicNumber: 39 }, Zr: { name: "Zirconium", atomicNumber: 40 },
+ Nb: { name: "Niobium", atomicNumber: 41 }, Mo: { name: "Molybdenum", atomicNumber: 42 },
+ Tc: { name: "Technetium", atomicNumber: 43 }, Ru: { name: "Ruthenium", atomicNumber: 44 },
+ Rh: { name: "Rhodium", atomicNumber: 45 }, Pd: { name: "Palladium", atomicNumber: 46 },
+ Ag: { name: "Silver", atomicNumber: 47 }, Cd: { name: "Cadmium", atomicNumber: 48 },
+ In: { name: "Indium", atomicNumber: 49 }, Sn: { name: "Tin", atomicNumber: 50 },
+ Sb: { name: "Antimony", atomicNumber: 51 }, Te: { name: "Tellurium", atomicNumber: 52 },
+ I: { name: "Iodine", atomicNumber: 53 }, Xe: { name: "Xenon", atomicNumber: 54 },
+ Cs: { name: "Cesium", atomicNumber: 55 }, Ba: { name: "Barium", atomicNumber: 56 },
+ La: { name: "Lanthanum", atomicNumber: 57 }, Ce: { name: "Cerium", atomicNumber: 58 },
+ Pr: { name: "Praseodymium", atomicNumber: 59 }, Nd: { name: "Neodymium", atomicNumber: 60 },
+ Pm: { name: "Promethium", atomicNumber: 61 }, Sm: { name: "Samarium", atomicNumber: 62 },
+ Eu: { name: "Europium", atomicNumber: 63 }, Gd: { name: "Gadolinium", atomicNumber: 64 },
+ Tb: { name: "Terbium", atomicNumber: 65 }, Dy: { name: "Dysprosium", atomicNumber: 66 },
+ Ho: { name: "Holmium", atomicNumber: 67 }, Er: { name: "Erbium", atomicNumber: 68 },
+ Tm: { name: "Thulium", atomicNumber: 69 }, Yb: { name: "Ytterbium", atomicNumber: 70 },
+ Lu: { name: "Lutetium", atomicNumber: 71 }, Hf: { name: "Hafnium", atomicNumber: 72 },
+ Ta: { name: "Tantalum", atomicNumber: 73 }, W: { name: "Tungsten", atomicNumber: 74 },
+ Re: { name: "Rhenium", atomicNumber: 75 }, Os: { name: "Osmium", atomicNumber: 76 },
+ Ir: { name: "Iridium", atomicNumber: 77 }, Pt: { name: "Platinum", atomicNumber: 78 },
+ Au: { name: "Gold", atomicNumber: 79 }, Tl: { name: "Thallium", atomicNumber: 81 },
+ Pb: { name: "Lead", atomicNumber: 82 }, Bi: { name: "Bismuth", atomicNumber: 83 },
+ Po: { name: "Polonium", atomicNumber: 84 }, At: { name: "Astatine", atomicNumber: 85 },
+ Rn: { name: "Radon", atomicNumber: 86 }, Fr: { name: "Francium", atomicNumber: 87 },
+ Ra: { name: "Radium", atomicNumber: 88 }, Ac: { name: "Actinium", atomicNumber: 89 },
+ Th: { name: "Thorium", atomicNumber: 90 }, Pa: { name: "Protactinium", atomicNumber: 91 },
+ U: { name: "Uranium", atomicNumber: 92 }, Np: { name: "Neptunium", atomicNumber: 93 },
+ Pu: { name: "Plutonium", atomicNumber: 94 }, Am: { name: "Americium", atomicNumber: 95 },
+ Cm: { name: "Curium", atomicNumber: 96 }, Bk: { name: "Berkelium", atomicNumber: 97 },
+ Cf: { name: "Californium", atomicNumber: 98 }, Es: { name: "Einsteinium", atomicNumber: 99 },
+ Fm: { name: "Fermium", atomicNumber: 100 }, Md: { name: "Mendelevium", atomicNumber: 101 },
+ No: { name: "Nobelium", atomicNumber: 102 },
+ }
+ },
+ mastery: { overallPct: 0, chunks: {}, elements: {} },
+ createdAt: '2026-03-08T00:00:00.000Z',
+ updatedAt: '2026-03-08T00:00:00.000Z',
+};
+
+// =============================================================================
+// DATA ACCESS
+// =============================================================================
+
+async function loadMemoryItems() {
+ const data = await readJSONFile(MEMORY_ITEMS_FILE, { items: [] }, { allowArray: false });
+ const items = data?.items && Array.isArray(data.items) ? data.items : [];
+
+ // Ensure built-in Elements Song is always present
+ const hasElements = items.some(i => i.id === 'elements-song');
+ if (!hasElements) {
+ items.unshift(structuredClone(ELEMENTS_SONG));
+ }
+
+ return items;
+}
+
+async function saveMemoryItems(items) {
+ await ensureDir(MEATSPACE_DIR);
+ await writeFile(MEMORY_ITEMS_FILE, JSON.stringify({ items }, null, 2));
+}
+
+async function loadTrainingLog() {
+ return readJSONFile(TRAINING_LOG_FILE, { entries: [] }, { allowArray: false });
+}
+
+async function saveTrainingLog(log) {
+ await ensureDir(MEATSPACE_DIR);
+ await writeFile(TRAINING_LOG_FILE, JSON.stringify(log, null, 2));
+}
+
+// =============================================================================
+// MEMORY ITEMS CRUD
+// =============================================================================
+
+export async function getMemoryItems() {
+ return loadMemoryItems();
+}
+
+export async function getMemoryItem(id) {
+ const items = await loadMemoryItems();
+ return items.find(i => i.id === id) || null;
+}
+
+export async function createMemoryItem(data) {
+ const items = await loadMemoryItems();
+ const now = new Date().toISOString();
+
+ const item = {
+ id: randomUUID(),
+ title: data.title,
+ type: data.type || 'text',
+ builtin: false,
+ content: {
+ lines: (data.lines || []).map(l => ({
+ text: l.text || l,
+ ...(l.elements ? { elements: l.elements } : {})
+ })),
+ chunks: data.chunks || autoChunk(data.lines || []),
+ },
+ mastery: { overallPct: 0, chunks: {}, elements: {} },
+ createdAt: now,
+ updatedAt: now,
+ };
+
+ items.push(item);
+ await saveMemoryItems(items);
+ console.log(`🧠 Memory item created: "${item.title}"`);
+ return item;
+}
+
+export async function updateMemoryItem(id, updates) {
+ const items = await loadMemoryItems();
+ const idx = items.findIndex(i => i.id === id);
+ if (idx === -1) return null;
+ if (items[idx].builtin) {
+ // Only allow mastery updates on built-in items
+ if (updates.mastery) {
+ items[idx].mastery = updates.mastery;
+ items[idx].updatedAt = new Date().toISOString();
+ await saveMemoryItems(items);
+ return items[idx];
+ }
+ return items[idx];
+ }
+
+ const item = items[idx];
+ if (updates.title) item.title = updates.title;
+ if (updates.type) item.type = updates.type;
+ if (updates.lines) {
+ item.content.lines = updates.lines.map(l => ({
+ text: l.text || l,
+ ...(l.elements ? { elements: l.elements } : {})
+ }));
+ }
+ if (updates.chunks) {
+ item.content.chunks = updates.chunks;
+ }
+ item.updatedAt = new Date().toISOString();
+ await saveMemoryItems(items);
+ console.log(`🧠 Memory item updated: "${item.title}"`);
+ return item;
+}
+
+export async function deleteMemoryItem(id) {
+ const items = await loadMemoryItems();
+ const idx = items.findIndex(i => i.id === id);
+ if (idx === -1) return null;
+ if (items[idx].builtin) return null; // Can't delete built-in items
+ const removed = items.splice(idx, 1)[0];
+ await saveMemoryItems(items);
+ console.log(`🧠 Memory item deleted: "${removed.title}"`);
+ return removed;
+}
+
+// =============================================================================
+// PRACTICE & MASTERY
+// =============================================================================
+
+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 now = new Date().toISOString();
+
+ // Update chunk mastery
+ if (chunkId) {
+ if (!item.mastery.chunks[chunkId]) {
+ item.mastery.chunks[chunkId] = { correct: 0, attempts: 0, lastPracticed: null };
+ }
+ const chunk = item.mastery.chunks[chunkId];
+ chunk.attempts += results.length;
+ chunk.correct += results.filter(r => r.correct).length;
+ chunk.lastPracticed = now;
+ }
+
+ // Update element-level mastery (for elements song)
+ if (results) {
+ for (const r of results) {
+ if (r.element) {
+ if (!item.mastery.elements[r.element]) {
+ item.mastery.elements[r.element] = { correct: 0, attempts: 0 };
+ }
+ item.mastery.elements[r.element].attempts++;
+ if (r.correct) item.mastery.elements[r.element].correct++;
+ }
+ }
+ }
+
+ // Recompute overall mastery percentage
+ item.mastery.overallPct = computeOverallMastery(item);
+ item.updatedAt = now;
+ await saveMemoryItems(items);
+
+ // Log the practice session
+ const log = await loadTrainingLog();
+ log.entries.push({
+ id: randomUUID(),
+ memoryItemId: id,
+ mode,
+ chunkId: chunkId || null,
+ correct: results.filter(r => r.correct).length,
+ total: results.length,
+ totalMs: totalMs || 0,
+ date: now,
+ });
+ await saveTrainingLog(log);
+
+ console.log(`🧠 Practice logged: "${item.title}" mode=${mode} ${results.filter(r => r.correct).length}/${results.length}`);
+ return { mastery: item.mastery, practiceId: log.entries[log.entries.length - 1].id };
+}
+
+export async function getMastery(id) {
+ const item = await getMemoryItem(id);
+ if (!item) return null;
+ return item.mastery;
+}
+
+export async function getTrainingLog(memoryItemId, limit = 50) {
+ const log = await loadTrainingLog();
+ let entries = log.entries || [];
+ if (memoryItemId) entries = entries.filter(e => e.memoryItemId === memoryItemId);
+ return entries.slice(-limit);
+}
+
+// =============================================================================
+// DRILL GENERATION (for POST sessions)
+// =============================================================================
+
+/**
+ * Generate a memory drill for a POST session.
+ * Picks the memory item with the lowest mastery (or user-configured item)
+ * and creates a fill-in-the-blank or sequence recall exercise.
+ */
+export async function generateMemoryDrill(config = {}) {
+ const items = await loadMemoryItems();
+ if (!items.length) return null;
+
+ // Pick target item — configured or lowest mastery
+ let item;
+ if (config.memoryItemId) {
+ item = items.find(i => i.id === config.memoryItemId);
+ }
+ if (!item) {
+ item = items.reduce((lowest, i) => i.mastery.overallPct < lowest.mastery.overallPct ? i : lowest, items[0]);
+ }
+
+ const mode = config.mode || 'fill-blank';
+ const count = config.count || 5;
+
+ switch (mode) {
+ case 'fill-blank':
+ return generateFillBlank(item, count);
+ case 'sequence':
+ return generateSequenceRecall(item, count);
+ case 'element-flash':
+ return generateElementFlash(item, count);
+ default:
+ return generateFillBlank(item, count);
+ }
+}
+
+function generateFillBlank(item, count) {
+ const lines = item.content.lines.filter(l => l.text.trim().length > 0);
+ if (!lines.length) return null;
+
+ const questions = [];
+ const shuffled = [...lines].sort(() => Math.random() - 0.5).slice(0, Math.min(count, lines.length));
+
+ for (const line of shuffled) {
+ const words = line.text.split(/\s+/);
+ if (words.length < 3) continue;
+
+ // Blank out ~30-50% of words, preferring element names if present
+ const blankedIndices = new Set();
+ const blankCount = Math.max(1, Math.floor(words.length * (0.3 + Math.random() * 0.2)));
+
+ // Prioritize element names for blanking
+ if (line.elements?.length) {
+ for (const sym of line.elements) {
+ const elementName = item.content.elementMap?.[sym]?.name?.toLowerCase();
+ if (elementName) {
+ const idx = words.findIndex((w, i) => !blankedIndices.has(i) && w.toLowerCase().replace(/[,.]$/, '') === elementName);
+ if (idx >= 0 && blankedIndices.size < blankCount) blankedIndices.add(idx);
+ }
+ }
+ }
+
+ // Fill remaining blanks randomly
+ while (blankedIndices.size < blankCount) {
+ blankedIndices.add(Math.floor(Math.random() * words.length));
+ }
+
+ const display = words.map((w, i) => blankedIndices.has(i) ? '____' : w).join(' ');
+ const answers = [...blankedIndices].sort((a, b) => a - b).map(i => ({
+ index: i,
+ word: words[i].replace(/[,.]$/, ''),
+ element: line.elements?.length ? findElementForWord(words[i], item.content.elementMap) : null,
+ }));
+
+ questions.push({
+ prompt: display,
+ fullText: line.text,
+ answers,
+ chunkId: findChunkForLine(item, lines.indexOf(line)),
+ });
+ }
+
+ return {
+ type: 'memory-fill-blank',
+ memoryItemId: item.id,
+ memoryItemTitle: item.title,
+ config: { count },
+ questions,
+ };
+}
+
+function generateSequenceRecall(item, count) {
+ const lines = item.content.lines.filter(l => l.text.trim().length > 0);
+ if (lines.length < 2) return null;
+
+ const questions = [];
+ const indices = [...Array(lines.length - 1).keys()].sort(() => Math.random() - 0.5).slice(0, Math.min(count, lines.length - 1));
+
+ for (const idx of indices) {
+ questions.push({
+ prompt: lines[idx].text,
+ promptLabel: 'What comes next?',
+ expected: lines[idx + 1].text,
+ chunkId: findChunkForLine(item, idx),
+ });
+ }
+
+ return {
+ type: 'memory-sequence',
+ memoryItemId: item.id,
+ memoryItemTitle: item.title,
+ config: { count },
+ questions,
+ };
+}
+
+function generateElementFlash(item, count) {
+ if (item.id !== 'elements-song' || !item.content.elementMap) return null;
+
+ const elements = Object.entries(item.content.elementMap);
+ const shuffled = [...elements].sort(() => Math.random() - 0.5).slice(0, Math.min(count, elements.length));
+
+ const questions = shuffled.map(([symbol, info]) => {
+ // Randomly ask name→symbol or symbol→name
+ const askSymbol = Math.random() > 0.5;
+ return askSymbol
+ ? { prompt: info.name, promptLabel: 'Symbol?', expected: symbol, element: symbol, direction: 'name-to-symbol' }
+ : { prompt: `${symbol} (${info.atomicNumber})`, promptLabel: 'Element name?', expected: info.name, element: symbol, direction: 'symbol-to-name' };
+ });
+
+ return {
+ type: 'memory-element-flash',
+ memoryItemId: item.id,
+ memoryItemTitle: item.title,
+ config: { count },
+ questions,
+ };
+}
+
+// =============================================================================
+// HELPERS
+// =============================================================================
+
+function computeOverallMastery(item) {
+ // For elements song: mastery is based on per-element accuracy
+ if (item.id === 'elements-song' && item.content.elementMap) {
+ const totalElements = Object.keys(item.content.elementMap).length;
+ if (totalElements === 0) return 0;
+ let masteredCount = 0;
+ for (const sym of Object.keys(item.content.elementMap)) {
+ const m = item.mastery.elements[sym];
+ if (m && m.attempts >= 3 && m.correct / m.attempts >= 0.8) masteredCount++;
+ }
+ return Math.round((masteredCount / totalElements) * 100);
+ }
+
+ // For generic items: mastery is based on chunk accuracy
+ const chunks = Object.values(item.mastery.chunks);
+ if (!chunks.length) return 0;
+ const avgAccuracy = chunks.reduce((sum, c) => sum + (c.attempts > 0 ? c.correct / c.attempts : 0), 0) / chunks.length;
+ return Math.round(avgAccuracy * 100);
+}
+
+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;
+}
+
+function findElementForWord(word, elementMap) {
+ if (!elementMap) return null;
+ const clean = word.toLowerCase().replace(/[,.\s]/g, '');
+ for (const [symbol, info] of Object.entries(elementMap)) {
+ if (info.name.toLowerCase() === clean) return symbol;
+ }
+ return null;
+}
+
+/**
+ * Auto-chunk content into groups of ~4 lines
+ */
+function autoChunk(lines) {
+ const chunkSize = 4;
+ const chunks = [];
+ for (let i = 0; i < lines.length; i += chunkSize) {
+ const end = Math.min(i + chunkSize - 1, lines.length - 1);
+ chunks.push({
+ id: `chunk-${Math.floor(i / chunkSize) + 1}`,
+ lineRange: [i, end],
+ label: `Part ${Math.floor(i / chunkSize) + 1}`,
+ });
+ }
+ return chunks;
+}
+
+export { ELEMENTS_SONG };