Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: custom memory items with spaced repetition (M55 P6)
Adam Eivy9f4401c35a3c
diff --git a/client/src/components/meatspace/post/MemoryBuilder.jsx b/client/src/components/meatspace/post/MemoryBuilder.jsxindex b83a297738..cff13956cd 100644--- a/client/src/components/meatspace/post/MemoryBuilder.jsx+++ b/client/src/components/meatspace/post/MemoryBuilder.jsx@@ -1,13 +1,28 @@import { useState, useEffect } from 'react';-import { Brain, ChevronLeft, Plus, Trash2, BookOpen, Zap, FlaskConical, Eye } from 'lucide-react';-import { getMemoryItems, deleteMemoryItem } from '../../../services/api';+import { Brain, ChevronLeft, Plus, Trash2, BookOpen, Zap, FlaskConical, Eye, X, Save } from 'lucide-react';+import { getMemoryItems, createMemoryItem, deleteMemoryItem } from '../../../services/api';import MemoryPractice from './MemoryPractice';import ElementsSong from './ElementsSong';+const ITEM_TYPES = [+ { id: 'song', label: 'Song' },+ { id: 'poem', label: 'Poem' },+ { id: 'speech', label: 'Speech' },+ { id: 'sequence', label: 'Sequence' },+ { id: 'text', label: 'Text' },+];+export default function MemoryBuilder({ onBack }) {const [items, setItems] = useState([]);const [selectedItem, setSelectedItem] = useState(null);- const [view, setView] = useState('list'); // list, practice, elements+ const [view, setView] = useState('list'); // list, practice, elements, create+ const [creating, setCreating] = useState(false);++ // Create form state+ const [newTitle, setNewTitle] = useState('');+ const [newType, setNewType] = useState('text');+ const [newContent, setNewContent] = useState('');+ const [saving, setSaving] = useState(false);useEffect(() => {loadItems();@@ -38,6 +53,34 @@ export default function MemoryBuilder({ onBack }) {setSelectedItem(null);}+ function resetCreateForm() {+ setNewTitle('');+ setNewType('text');+ setNewContent('');+ setCreating(false);+ }++ async function handleCreate() {+ if (!newTitle.trim() || !newContent.trim()) return;+ setSaving(true);++ // Split content into lines, preserving blank lines for chunk detection+ const rawLines = newContent.split('\n');+ const lines = rawLines.map(text => ({ text }));++ const item = await createMemoryItem({+ title: newTitle.trim(),+ type: newType,+ lines,+ }).catch(() => null);++ setSaving(false);+ if (item) {+ setItems(prev => [...prev, item]);+ resetCreateForm();+ }+ }+if (view === 'elements' && selectedItem) {return (<ElementsSong@@ -67,12 +110,97 @@ export default function MemoryBuilder({ onBack }) {<Brain size={24} className="text-emerald-400" /><h2 className="text-xl font-bold text-white">Memory Builder</h2></div>+ {!creating && (+ <button+ onClick={() => setCreating(true)}+ 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"+ >+ <Plus size={14} />+ Add Item+ </button>+ )}</div><p className="text-gray-400 text-sm">Train your memory with songs, poems, speeches, and sequences. Track mastery and practice weak spots.</p>+ {/* Create Form */}+ {creating && (+ <div className="bg-port-card border border-port-accent/30 rounded-lg p-5 space-y-4">+ <div className="flex items-center justify-between">+ <h3 className="text-white font-medium">Add Memory Item</h3>+ <button onClick={resetCreateForm} className="text-gray-500 hover:text-white transition-colors">+ <X size={16} />+ </button>+ </div>++ <div>+ <label className="block text-gray-400 text-xs mb-1.5">Title</label>+ <input+ type="text"+ value={newTitle}+ onChange={e => setNewTitle(e.target.value)}+ placeholder="e.g. The Raven, Gettysburg Address, Pi digits..."+ maxLength={200}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-white text-sm placeholder-gray-600 focus:border-port-accent focus:outline-none"+ />+ </div>++ <div>+ <label className="block text-gray-400 text-xs mb-1.5">Type</label>+ <div className="flex flex-wrap gap-2">+ {ITEM_TYPES.map(t => (+ <button+ key={t.id}+ onClick={() => setNewType(t.id)}+ className={`px-3 py-1.5 text-xs rounded-lg border transition-colors ${+ newType === t.id+ ? 'bg-port-accent/20 border-port-accent text-port-accent'+ : 'bg-port-bg border-port-border text-gray-400 hover:text-white'+ }`}+ >+ {t.label}+ </button>+ ))}+ </div>+ </div>++ <div>+ <label className="block text-gray-400 text-xs mb-1.5">+ Content <span className="text-gray-600">(one line per row; blank lines create chunk boundaries)</span>+ </label>+ <textarea+ value={newContent}+ onChange={e => setNewContent(e.target.value)}+ placeholder={"Paste or type your content here.\nEach line becomes a learnable unit.\n\nBlank lines separate chunks/verses."}+ rows={12}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-white text-sm placeholder-gray-600 focus:border-port-accent focus:outline-none resize-y font-mono leading-relaxed"+ />+ {newContent.trim() && (+ <ContentPreview content={newContent} />+ )}+ </div>++ <div className="flex justify-end gap-3">+ <button+ onClick={resetCreateForm}+ className="px-4 py-2 text-sm text-gray-400 hover:text-white transition-colors"+ >+ Cancel+ </button>+ <button+ onClick={handleCreate}+ disabled={!newTitle.trim() || !newContent.trim() || saving}+ className="flex items-center gap-1.5 px-4 py-2 text-sm bg-port-success hover:bg-port-success/80 disabled:opacity-50 text-white rounded-lg transition-colors"+ >+ <Save size={14} />+ {saving ? 'Saving...' : 'Save Item'}+ </button>+ </div>+ </div>+ )}+{/* Memory Items */}<div className="space-y-3">{items.map(item => (@@ -88,6 +216,7 @@ export default function MemoryBuilder({ onBack }) {<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>+ <span>{item.content?.chunks?.length || 0} chunks</span>{item.builtin && <span className="text-emerald-500">built-in</span>}</div></div>@@ -126,6 +255,30 @@ export default function MemoryBuilder({ onBack }) {);}+function ContentPreview({ content }) {+ const rawLines = content.split('\n');+ const nonEmptyLines = rawLines.filter(l => l.trim().length > 0);++ // Count chunks (groups separated by blank lines)+ let chunkCount = 0;+ let inChunk = false;+ for (const line of rawLines) {+ if (line.trim()) {+ if (!inChunk) { chunkCount++; inChunk = true; }+ } else {+ inChunk = false;+ }+ }+ if (chunkCount < 2) chunkCount = Math.ceil(nonEmptyLines.length / 4);++ return (+ <div className="mt-2 flex gap-4 text-xs text-gray-500">+ <span>{nonEmptyLines.length} lines</span>+ <span>{chunkCount} chunks</span>+ </div>+ );+}+function ItemIcon({ type, builtin }) {if (builtin) return <FlaskConical size={20} className="text-emerald-400 shrink-0" />;switch (type) {diff --git a/client/src/components/meatspace/post/MemoryPractice.jsx b/client/src/components/meatspace/post/MemoryPractice.jsxindex b9790c92fc..69cec69eb2 100644--- a/client/src/components/meatspace/post/MemoryPractice.jsx+++ b/client/src/components/meatspace/post/MemoryPractice.jsx@@ -1,12 +1,13 @@import { useState, useRef, useEffect } from 'react';-import { ChevronLeft, Play, Check, X, SkipForward, RotateCcw } from 'lucide-react';-import { submitMemoryPractice } from '../../../services/api';+import { ChevronLeft, Play, Check, X, SkipForward, RotateCcw, Target, ChevronDown } from 'lucide-react';+import { submitMemoryPractice, getChunkMastery } 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' },+ { id: 'spaced', label: 'Spaced Repetition', desc: 'Focus on your weakest chunks with graduated hints' },];export default function MemoryPractice({ item, onBack, onComplete }) {@@ -19,11 +20,26 @@ export default function MemoryPractice({ item, onBack, onComplete }) {const [startTime] = useState(Date.now());const inputRef = useRef(null);+ // Spaced repetition state+ const [chunkMastery, setChunkMastery] = useState(null);+ const [spacedChunkIdx, setSpacedChunkIdx] = useState(0);+ const [spacedLineIdx, setSpacedLineIdx] = useState(0);+const lines = item.content?.lines || [];+ const chunks = item.content?.chunks || [];useEffect(() => {if (mode && inputRef.current) inputRef.current.focus();- }, [mode, currentIdx]);+ }, [mode, currentIdx, spacedLineIdx]);++ // Load chunk mastery when entering spaced mode+ useEffect(() => {+ if (mode === 'spaced') {+ getChunkMastery(item.id).then(data => {+ setChunkMastery(data || []);+ }).catch(() => setChunkMastery([]));+ }+ }, [mode, item.id]);if (!mode) {return (@@ -44,11 +60,19 @@ export default function MemoryPractice({ item, onBack, onComplete }) {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="flex items-center gap-2">+ <div className="text-white font-medium">{m.label}</div>+ {m.id === 'spaced' && <Target size={14} className="text-port-accent" />}+ </div><div className="text-gray-500 text-sm mt-1">{m.desc}</div></button>))}</div>++ {/* Chunk mastery overview */}+ {chunks.length > 0 && (+ <ChunkMasteryOverview item={item} />+ )}</div>);}@@ -92,7 +116,7 @@ export default function MemoryPractice({ item, onBack, onComplete }) {<div className="flex gap-3"><button- onClick={() => { setMode(null); setResults([]); setCurrentIdx(0); setDone(false); setShowResult(null); }}+ onClick={() => { setMode(null); setResults([]); setCurrentIdx(0); setDone(false); setShowResult(null); setSpacedChunkIdx(0); setSpacedLineIdx(0); }}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} />@@ -109,6 +133,151 @@ export default function MemoryPractice({ item, onBack, onComplete }) {);}+ // SPACED REPETITION mode — focus on weakest chunks with graduated hints+ if (mode === 'spaced') {+ if (!chunkMastery) {+ return (+ <div className="space-y-6 max-w-2xl">+ <div className="text-gray-400 text-sm">Loading chunk mastery...</div>+ </div>+ );+ }++ if (chunkMastery.length === 0) {+ 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">Spaced Repetition — {item.title}</h2>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-6 text-center text-gray-500">+ No chunks available for spaced practice.+ </div>+ </div>+ );+ }++ const currentChunk = chunkMastery[spacedChunkIdx];+ if (!currentChunk) {+ // All chunks done+ savePractice('spaced', results);+ setDone(true);+ return null;+ }++ const [chunkStart, chunkEnd] = currentChunk.lineRange;+ const chunkLines = lines.slice(chunkStart, chunkEnd + 1).filter(l => l.text.trim());+ const currentLine = chunkLines[spacedLineIdx];++ if (!currentLine) {+ // Move to next chunk+ setSpacedChunkIdx(prev => prev + 1);+ setSpacedLineIdx(0);+ setAnswer('');+ setShowResult(null);+ return null;+ }++ // Graduated hints based on hintLevel:+ // 0 = show first letter of each word, 1 = show first letters of some, 2 = show word count only, 3 = no hints+ const hintLevel = currentChunk.hintLevel;+ const hintText = generateHint(currentLine.text, hintLevel);++ 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">Spaced — {item.title}</h2>+ <span className="text-gray-500 text-sm ml-auto">+ Chunk {spacedChunkIdx + 1}/{chunkMastery.length} • Line {spacedLineIdx + 1}/{chunkLines.length}+ </span>+ </div>++ <ProgressBar current={spacedChunkIdx * 10 + spacedLineIdx + 1} total={chunkMastery.length * 10} />++ {/* Chunk info */}+ <div className="flex items-center gap-3 text-xs">+ <span className="text-gray-500">{currentChunk.label}</span>+ <span className={`font-mono ${currentChunk.accuracy >= 80 ? 'text-port-success' : currentChunk.accuracy >= 40 ? 'text-port-warning' : 'text-gray-500'}`}>+ {currentChunk.accuracy}% mastery+ </span>+ <span className="text-gray-600">+ Hint level: {['Full', 'Partial', 'Minimal', 'None'][hintLevel]}+ </span>+ </div>++ <div className="bg-port-card border border-port-border rounded-lg p-6">+ {/* Show previous lines in chunk as context */}+ {spacedLineIdx > 0 && (+ <div className="mb-4 space-y-1">+ {chunkLines.slice(0, spacedLineIdx).map((l, i) => (+ <div key={i} className="text-gray-500 text-sm">{l.text}</div>+ ))}+ </div>+ )}++ <div className="text-gray-400 text-xs mb-2 uppercase tracking-wide">Recall this line:</div>+ {hintText && <div className="text-gray-600 text-sm font-mono mb-3">{hintText}</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: {currentLine.text}+ </div>+ )}+ </div>+ ) : (+ <textarea+ ref={inputRef}+ value={answer}+ onChange={e => setAnswer(e.target.value)}+ onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); checkSpacedAnswer(currentLine.text, currentChunk.id); } }}+ placeholder="Type the line..."+ className="w-full bg-port-bg border border-port-border rounded-lg px-4 py-3 text-white placeholder-gray-600 focus:border-port-accent focus:outline-none resize-none"+ rows={2}+ />+ )}+ </div>++ <div className="flex gap-3">+ {showResult ? (+ <button+ onClick={advanceSpaced}+ 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={() => checkSpacedAnswer(currentLine.text, currentChunk.id)}+ disabled={!answer.trim()}+ className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white rounded-lg transition-colors"+ >+ <Check size={16} />+ Check+ </button>+ <button+ onClick={() => { setAnswer(''); checkSpacedAnswer(currentLine.text, currentChunk.id, true); }}+ className="px-4 py-2.5 bg-port-card border border-port-border rounded-lg text-gray-400 hover:text-white transition-colors"+ >+ <SkipForward size={16} />+ </button>+ </>+ )}+ </div>+ </div>+ );+ }+// LEARN mode — progressive revealif (mode === 'learn') {return (@@ -420,6 +589,46 @@ export default function MemoryPractice({ item, onBack, onComplete }) {}}+ function checkSpacedAnswer(expected, chunkId, skipped = false) {+ const isCorrect = !skipped && fuzzyMatch(answer, expected);+ setResults(prev => [...prev, { correct: isCorrect, expected, answered: skipped ? '' : answer, chunkId }]);+ setShowResult(isCorrect ? 'correct' : 'wrong');+ }++ function advanceSpaced() {+ const currentChunk = chunkMastery[spacedChunkIdx];+ const [chunkStart, chunkEnd] = currentChunk.lineRange;+ const chunkLines = lines.slice(chunkStart, chunkEnd + 1).filter(l => l.text.trim());++ if (spacedLineIdx + 1 < chunkLines.length) {+ setSpacedLineIdx(prev => prev + 1);+ } else {+ // Save practice for this chunk, move to next+ const chunkResults = results.filter(r => r.chunkId === currentChunk.id);+ if (chunkResults.length > 0) {+ submitMemoryPractice(item.id, {+ mode: 'sequence',+ chunkId: currentChunk.id,+ results: chunkResults.map(r => ({+ correct: r.correct,+ expected: r.expected,+ answered: r.answered,+ })),+ totalMs: Date.now() - startTime,+ }).catch(() => {});+ }++ if (spacedChunkIdx + 1 < chunkMastery.length) {+ setSpacedChunkIdx(prev => prev + 1);+ setSpacedLineIdx(0);+ } else {+ setDone(true);+ }+ }+ setAnswer('');+ setShowResult(null);+ }+async function savePractice(practiceMode, practiceResults) {const chunkId = findChunkForLine(item, currentIdx);await submitMemoryPractice(item.id, {@@ -437,6 +646,79 @@ export default function MemoryPractice({ item, onBack, onComplete }) {}}+/**+ * Generate graduated hints based on mastery level.+ * hintLevel 0: show first letter of each word + word length+ * hintLevel 1: show first letter of every other word+ * hintLevel 2: show word count only+ * hintLevel 3: no hints+ */+function generateHint(text, hintLevel) {+ if (hintLevel >= 3) return null;++ const words = text.split(/\s+/);++ if (hintLevel === 0) {+ // Full hints: first letter + underscores for length+ return words.map(w => {+ const clean = w.replace(/[,.\-!?'"]/g, '');+ if (clean.length <= 1) return w;+ return w[0] + '_'.repeat(clean.length - 1) + w.slice(clean.length);+ }).join(' ');+ }++ if (hintLevel === 1) {+ // Partial: first letter of every other word+ return words.map((w, i) => {+ if (i % 2 === 0) {+ const clean = w.replace(/[,.\-!?'"]/g, '');+ return clean.length > 1 ? w[0] + '___' : w;+ }+ return '____';+ }).join(' ');+ }++ // Minimal: word count only+ return `(${words.length} words)`;+}++function ChunkMasteryOverview({ item }) {+ const [expanded, setExpanded] = useState(false);+ const chunks = item.content?.chunks || [];+ if (!chunks.length) return null;++ return (+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">+ <button+ onClick={() => setExpanded(!expanded)}+ className="w-full flex items-center justify-between p-3 text-left hover:bg-port-bg/50 transition-colors"+ >+ <span className="text-gray-400 text-xs font-medium">Chunk Mastery</span>+ <ChevronDown size={14} className={`text-gray-500 transition-transform ${expanded ? 'rotate-180' : ''}`} />+ </button>+ {expanded && (+ <div className="px-3 pb-3 space-y-1.5">+ {chunks.map(chunk => {+ const stats = item.mastery?.chunks?.[chunk.id];+ const accuracy = stats?.attempts > 0 ? Math.round((stats.correct / stats.attempts) * 100) : 0;+ const barColor = accuracy >= 80 ? 'bg-port-success' : accuracy >= 40 ? 'bg-port-warning' : 'bg-gray-600';++ return (+ <div key={chunk.id} className="flex items-center gap-2">+ <span className="text-xs text-gray-500 w-16 truncate">{chunk.label}</span>+ <div className="flex-1 h-1.5 bg-port-border rounded-full overflow-hidden">+ <div className={`h-full rounded-full ${barColor}`} style={{ width: `${accuracy}%` }} />+ </div>+ <span className="text-xs font-mono text-gray-500 w-10 text-right">{accuracy}%</span>+ </div>+ );+ })}+ </div>+ )}+ </div>+ );+}+function SpeedRunLine({ line, index, onResult }) {const [revealed, setRevealed] = useState(false);const [marked, setMarked] = useState(null);diff --git a/client/src/services/api.js b/client/src/services/api.jsindex c07feb83ba..519990b40e 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1532,6 +1532,7 @@ export const submitMemoryPractice = (id, data) => request(`/meatspace/post/memorbody: JSON.stringify(data)});export const getMemoryMastery = (id) => request(`/meatspace/post/memory-items/${id}/mastery`);+export const getChunkMastery = (id) => request(`/meatspace/post/memory-items/${id}/chunk-mastery`);export const generateMemoryDrill = (data) => request('/meatspace/post/memory-drill', {method: 'POST',body: JSON.stringify(data)diff --git a/server/routes/meatspace.js b/server/routes/meatspace.jsindex 6c1ba3a0c6..441ec7a936 100644--- a/server/routes/meatspace.js+++ b/server/routes/meatspace.js@@ -589,6 +589,16 @@ router.get('/post/memory-items/:id/mastery', asyncHandler(async (req, res) => {res.json(mastery);}));+/**+ * GET /api/meatspace/post/memory-items/:id/chunk-mastery+ * Get chunk mastery order for spaced repetition practice+ */+router.get('/post/memory-items/:id/chunk-mastery', 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(memoryService.getChunkMasteryOrder(item));+}));+/*** POST /api/meatspace/post/memory-drill* Generate a memory drill for a POST sessiondiff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.jsindex beb229dd2f..2613e0d5fb 100644--- a/server/services/meatspacePostMemory.js+++ b/server/services/meatspacePostMemory.js@@ -168,17 +168,28 @@ export async function createMemoryItem(data) {const items = await loadMemoryItems();const now = new Date().toISOString();+ const rawLines = (data.lines || []).map(l => ({+ text: l.text || l,+ ...(l.elements ? { elements: l.elements } : {})+ }));++ // Auto-chunk uses all lines (including blanks for boundary detection)+ const chunks = data.chunks || autoChunk(rawLines);++ // Store only non-empty lines for practice+ const contentLines = rawLines.filter(l => l.text.trim().length > 0);++ // Remap chunk lineRanges to match filtered line indices+ const remappedChunks = remapChunksAfterFilter(rawLines, contentLines, chunks);+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 || []),+ lines: contentLines,+ chunks: remappedChunks,},mastery: { overallPct: 0, chunks: {}, elements: {} },createdAt: now,@@ -187,7 +198,7 @@ export async function createMemoryItem(data) {items.push(item);await saveMemoryItems(items);- console.log(`🧠 Memory item created: "${item.title}"`);+ console.log(`🧠 Memory item created: "${item.title}" (${contentLines.length} lines, ${remappedChunks.length} chunks)`);return item;}@@ -315,6 +326,7 @@ export async function getTrainingLog(memoryItemId, limit = 50) {* 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.+ * Uses spaced repetition: focuses on lowest-mastery chunks.*/export async function generateMemoryDrill(config = {}) {const items = await loadMemoryItems();@@ -344,6 +356,27 @@ export async function generateMemoryDrill(config = {}) {}}+/**+ * Get chunk mastery stats for spaced repetition.+ * Returns chunks sorted by mastery (lowest first) with hint level.+ */+export function getChunkMasteryOrder(item) {+ const chunks = item.content?.chunks || [];+ return chunks.map(chunk => {+ const stats = item.mastery?.chunks?.[chunk.id];+ const accuracy = stats?.attempts > 0 ? stats.correct / stats.attempts : 0;+ // Hint level: 0 = full hints, 1 = partial, 2 = minimal, 3 = no hints+ const hintLevel = accuracy >= 0.9 ? 3 : accuracy >= 0.7 ? 2 : accuracy >= 0.4 ? 1 : 0;+ return {+ ...chunk,+ accuracy: Math.round(accuracy * 100),+ attempts: stats?.attempts || 0,+ lastPracticed: stats?.lastPracticed || null,+ hintLevel,+ };+ }).sort((a, b) => a.accuracy - b.accuracy);+}+function generateFillBlank(item, count) {const lines = item.content.lines.filter(l => l.text.trim().length > 0);if (!lines.length) return null;@@ -489,9 +522,40 @@ function findElementForWord(word, elementMap) {}/**- * Auto-chunk content into groups of ~4 lines+ * Auto-chunk content into learnable segments.+ * Splits on blank lines first (verse/stanza boundaries).+ * Falls back to groups of ~4 lines if no blank lines.*/function autoChunk(lines) {+ const texts = lines.map(l => (typeof l === 'string' ? l : l.text) || '');++ // Check for blank-line boundaries+ const groups = [];+ let current = [];+ let startIdx = 0;+ for (let i = 0; i < texts.length; i++) {+ if (texts[i].trim() === '' && current.length > 0) {+ groups.push({ start: startIdx, end: i - 1 });+ current = [];+ startIdx = i + 1;+ } else if (texts[i].trim() !== '') {+ current.push(i);+ }+ }+ if (current.length > 0) {+ groups.push({ start: startIdx, end: texts.length - 1 });+ }++ // If blank-line splitting produced reasonable chunks (2+), use them+ if (groups.length >= 2) {+ return groups.map((g, i) => ({+ id: `chunk-${i + 1}`,+ lineRange: [g.start, g.end],+ label: `Part ${i + 1}`,+ }));+ }++ // Fallback: fixed-size groups of ~4 linesconst chunkSize = 4;const chunks = [];for (let i = 0; i < lines.length; i += chunkSize) {@@ -505,4 +569,36 @@ function autoChunk(lines) {return chunks;}+/**+ * Remap chunk lineRanges after blank lines are filtered out.+ * Maps original indices to new indices in the filtered array.+ */+function remapChunksAfterFilter(rawLines, filteredLines, chunks) {+ // Build mapping: original index → filtered index+ const indexMap = new Map();+ let filteredIdx = 0;+ for (let i = 0; i < rawLines.length; i++) {+ const text = typeof rawLines[i] === 'string' ? rawLines[i] : rawLines[i].text;+ if (text.trim().length > 0) {+ indexMap.set(i, filteredIdx);+ filteredIdx++;+ }+ }++ return chunks.map(chunk => {+ const [origStart, origEnd] = chunk.lineRange;+ // Find first and last non-empty lines in this chunk's range+ let newStart = null;+ let newEnd = null;+ for (let i = origStart; i <= origEnd; i++) {+ if (indexMap.has(i)) {+ if (newStart === null) newStart = indexMap.get(i);+ newEnd = indexMap.get(i);+ }+ }+ if (newStart === null) return null; // Empty chunk+ return { ...chunk, lineRange: [newStart, newEnd] };+ }).filter(Boolean);+}+export { ELEMENTS_SONG };